/** Ajax
 **/
function serializeForm(form) {
  if (typeof(form) != 'object') {
    return false;
  }
  var result = new Array();
  var g = function(n) {
    return form.getElementsByTagName(n)
  };
  var nv = function(i, e){
    if (e.name) result[e.name] = (browser.msie && !e.value) ? form[e.name].value : e.value;
  };
  each(g('input'), function(i, e) {
    if ((e.type != 'radio' && e.type != 'checkbox') || e.checked) return nv(i, e);
  });
  each(g('select'), nv);
  each(g('textarea'), nv);

  return result;
}

function ajx2q(qa) {
 var query = [], q, i =0;
 for (var key in qa) {
   if (qa[key] === undefined || qa[key] === null || typeof(qa[key]) == 'function') continue;
   if (isArray(qa[key])) {
     for (var i = 0; i < qa[key].length; ++i) {
       if (qa[key][i] === undefined || qa[key][i] === null || typeof(qa[key][i]) == 'function') continue;
       query.push(encodeURIComponent(key) + '[]=' + encodeURIComponent(qa[key][i]));
     }
   } else {
     query.push(encodeURIComponent(key) + '=' + encodeURIComponent(qa[key]));
   }
 }
 return query.join('&');
}
function q2o(q) {
 var t = q;
 if (typeof q == 'string') {
   var d=q.split('&'),v,i; t={};
   for (i=0; i<d.length; i++) {
     v=d[i].split('=');
     t[decodeURIComponent(v[0])] = decodeURIComponent(v[1]);
   }
 }
 return t;
}
function Ajax(onDone, onFail, eval_res) {
    var _t = this;
    this.onDone = onDone;
    this.onFail = onFail;
    var tram = null;

    if (!tram) {
        try { tram = new XMLHttpRequest(); }
        catch(e) { tram = null; }
        // alert('XMLHttpRequest');
    }
    if (!tram) {
        try { tram = new ActiveXObject("Msxml2.XMLHTTP"); }
        catch(e) { tram = null; }
        // alert('Msxml2.XMLHTTP');
    }
    if (!tram) {
        try { tram = new ActiveXObject("Microsoft.XMLHTTP"); }
        catch(e) { tram = null; }
        // alert('Microsoft.XMLHTTP');
    }
    if (!tram) {
        alert('Nu i pisec :-((((((((((((');
    }

    var readystatechange = function(url, data) {
        if(tram.readyState == 4 ) {
            if(tram.status >= 200 && tram.status < 300) {
                if(eval_res) parseRes();
                if( _t.onDone ) _t.onDone(extend(_t, {url: url, data: data}), tram.responseText);
            } else {
                _t.status = tram.status;
                _t.readyState = tram.readyState;
                if( _t.onFail ) _t.onFail(extend(_t, {url: url, data: data}), tram.responseText);
            }
        }
    };

    var parseRes = function() {
        if(!tram || !tram.responseText) return;
        var res = tram.responseText.replace(/^[\s\n]+/g, '');

        if(res.substr(0,10)=="<noscript>") {
            try {
                var arr = res.substr(10).split("</noscript>");
                eval(arr[0]);
                tram.responseText = arr[1];
            } catch(e) {
                debugLog('eval ajax script:' + e.message);
            }
        } else {}
    };

    this.get = function(u, d, f) {
        tram.onreadystatechange = function(){ readystatechange(u, d); };
        f = f || false;
        var q = (typeof(d) != 'string') ? ajx2q(d) : d;
        u = u + (q ? ('?'+q) : '');
        tram.open('GET', u, !f);

        tram.setRequestHeader("X-Requested-With", "XMLHttpRequest");
        tram.send('');
    };

    this.post = function(u, d, f){
        tram.onreadystatechange = function(){ readystatechange(u, d); };
        f = f || false;
        var q = (typeof(d) != 'string') ? ajx2q(d) : d;
        try {
            tram.open('POST', u, !f);
        } catch(e) {
            debugLog('ajax post error: '+e.message);
        }
        tram.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        tram.setRequestHeader("X-Requested-With", "XMLHttpRequest");
        // alert(q);
        tram.send(q);
    };
}

function activate_mobile(from_captcha, on_hide, hash) {
  if (from_captcha) {
    on_hide = function() {
      Ajax._captchaBox.show();
      if (!window.need_mobile_act) {
        triggerEvent(ge('captchaKey'), 'keypress', {keyCode: 13});
      }
    }
  }
  showBox('activate_mobile', 'activation.php', {act: 'activate_mobile_box', hash: hash}, false, true, {type: 'POPUP', hideOnClick: false, progress: 'activate_progress', onHide: on_hide}, ['css/al/reg.css']);
}

(function() {
    var ajaxObjs = {};
    window.Ajax.Get = function(p){
        var a = (p.key)?ajaxObjs[p.key]:null;
        if(!a){
            a = new Ajax(p.onDone, p.onFail, p.eval);
            if(p.key)ajaxObjs[p.key] = a;
        }
            a.get(p.url, p.query, p.sync);
    }
    window.Ajax.Post = function(p) {
        // alert('window.Ajax.Post');
        var a = (p.key) ? ajaxObjs[p.key] : null;
        if(!a) {
            a = new Ajax(p.onDone, p.onFail, p.eval);
            if(p.key)ajaxObjs[p.key] = a;
        }
        a.post(p.url, p.query, p.sync);
    }
    window.Ajax.postWithCaptcha = function(url, data, options) {
        var onSuccess, onFail, onCaptchaShow, onCaptchaHide, difficulty;
        if (!options) options = {};
        if (isFunction(options)) {
            onSuccess = options;
        } else {
            onSuccess = options.onSuccess;
            onFail = options.onFail;
            onCaptchaShow = options.onCaptchaShow;
            onCaptchaHide = options.onCaptchaHide;
        }
        difficulty = options.difficultCaptcha ? '' : 's=1&';
        var p = {};
        p = {
            url: url,
            query: data,
            onFail: function(ajaxObj, responseText) {
                if (isFunction(onFail)) onFail(ajaxObj, responseText);
                if (window.Ajax._captchaBox) {
                    window.Ajax._captchaBox.setOptions({onHide: function(){}}).hide();
                    if (isFunction(onCaptchaHide)) onCaptchaHide(true);
                }
            },
            onDone: function(ajaxObj, responseText) {
                var response;
                try {
                    response = eval('(' + responseText + ')');
                    if (response.ok && response.ok == -5) {
                        if (ge('please_confirm_mail')) {
                            response.ok = -4;
                        }
                    }
                    if (response.ok && response.ok == -5) {
                    if (isFunction(onCaptchaShow)) onCaptchaShow();
                    if (response.title || response.message) {
                        var box = new MessageBox({title: response.title || 'Подтверждение действия'});
                        box.addButton({label: global_close, onClick: box.hide});
                        box.content(response.message || 'Превышено ограничение на количество действий, попробуйте позже.').show();
                    } else {
                    window.validated = false;
                    activate_mobile(false, function() {
                    if (window.validated) {
                    Ajax.Post(p);
                    }
                    if (onCaptchaHide) onCaptchaHide(!window.need_mobile_act);
                    }, response.hash);
                    }
                    } else if (response.ok && response.ok == -4) {
                        if (isFunction(onCaptchaShow)) onCaptchaShow()
                        if (ge('please_confirm_mail')) {
                            show_change_mail_box(onCaptchaHide);
                        } else {
                            if (onCaptchaHide) onCaptchaHide();
                        }
                    } else if (response.ok && response.ok == -3) {
                        var t;
                        var iframe = document.createElement('iframe');
                        iframe.style.visibility = 'hidden';
                        iframe.style.position = 'absolute';
                        iframe.src = "http://login.vk.com/";
                        document.body.appendChild(iframe);
                        var onload = function() {
                            try {
                                var href = iframe.contentWindow.location.href;
                                if (href.indexOf('slogin') != -1) {
                                    if (href.indexOf('nonenone') != -1) {
                                        location.href= base_domain+'login.php?op=logout'; return false;
                                    } else {
                                        Ajax.Post(p);
                                    }
                                    clearInterval(t);
                                }
                            } catch(e) {}
                        }
                        if (browser.msie) {
                            t = setInterval(function() {
                                if (iframe.document.readyState == 'complete') {
                                    onload();
                                }
                            }, 200);
                        } else {
                            iframe.onload = onload;
                        }
                    } else if (response.ok && response.ok == -2) {
                        if (window.Ajax._captchaBox == undefined) {
                            window.Ajax._captchaBox = new MessageBox({title: getLang('captcha_enter_code'), width: 300});
                        }
                        if (response.difficult !== undefined) {
                            difficulty = intval(response.difficult) ? '' : 's=1&';
                        }
                        var box = window.Ajax._captchaBox;
                        box.removeButtons();
                        var key;
                        var onClick = function() {
                            removeEvent(key, 'keypress');
                            if (typeof(p.query) == 'object') {
                                extend(p.query, {'captcha_sid': response.captcha_sid, 'captcha_key': key.value});
                            } else {
                                p.query += '&captcha_sid=' + response.captcha_sid + '&captcha_key=' + key.value;
                            }
                            Ajax.Post(p);
                            hide('captchaKey');
                            show('captchaLoader');
                            return false;
                        };
                        var about_mobile_text = '';
                        if (window.need_mobile_act == 1 && !ge('please_confirm_mail')) {
                            about_mobile_text = global_try_to_activate.replace('{link}', '<a href="javascript: activate_mobile(true)">').replace('{/link}', '</a>');
                            about_mobile_text = '<div style="text-align: center; font-size: 10px; padding-top: 5px; line-height: 15px;">' + about_mobile_text + '</span>';
                        }
                        box.addButton({
                            label: getLang('captcha_cancel'),
                            style: 'button_no',
                            onClick: function(){
                                removeEvent(key, 'keypress');
                                box.hide();
                            }
                        });
                        box.addButton({label: getLang('captcha_send'), onClick: onClick});
                        box.setOptions({onHide: onCaptchaHide, bodyStyle: 'padding: 16px 14px' + (about_mobile_text.length ? ' 10px' : '')});
                        box.content('<div style="text-align: center; height: 76px"><a href="#" id="refreshCaptcha"><img id="captchaImg" class="captchaImg" src="'+base_domain+'captcha.php?' + difficulty + 'sid=' + response.captcha_sid + '"/></a><div></div><input id="captchaKey" class="inputText" name="captcha_key" type="text" style="width: 120px; margin: 3px 0px 0px;" maxlength="7"/><img id="captchaLoader" src="'+base_domain+'images/progress7.gif" style="display:none; margin-top: 13px;" /></div>' + about_mobile_text);
                        box.show();
                        if (isFunction(onCaptchaShow)) onCaptchaShow();
                        key = ge('captchaKey');
                        addEvent(key, 'keypress', function(e) {
                            if(e.keyCode==13) {
                                onClick();
                            }
                        });
                        addEvent(ge('refreshCaptcha'), 'click', onClick);
                        key.focus();
                    } else {
                        throw "Exit";
                    }
                } catch (e) { // if captcha test passed
                    if (options.json && response)
                        responseText = response;
                    else if (response && typeof(response.text) == 'string')
                        responseText = response.text;
                    if (window.Ajax._captchaBox) {
                        window.Ajax._captchaBox.setOptions({onHide: function(){}}).hide();
                        if (isFunction(onCaptchaHide))
                            onCaptchaHide(true);
                    }
                    if (isFunction(onSuccess))
                        onSuccess(ajaxObj, responseText);
                }
            }
        };
        // alert(p['query']);
        Ajax.Post(p);
    }
    window.Ajax.History = function(url, query, update) {
        ajaxHistory.useCache = false;
        ajaxHistory.prepare({url: url, done: function(o,t) {
            try {
                var r = eval('('+t+')'); 
                if(r.data)Ajax.current = r.data; 
                update(r);
            } catch (e) {
                debugLog(e);
            }
        }, def: query});
        Ajax.current = query;
    };
    window.Ajax.Go = function(query) {
        var q = extend(clone(Ajax.current), query);
        ajaxHistory.go(q);
    }
    window.Ajax.Send = Ajax.postWithCaptcha;
}
)();

var ajaxHistory = $ah = new (function(){
       var _t = this;

       var curHash = "";
       var curHashes = {};
       var frame = null;
       var frame_doc = function() {
         return frame.contentDocument ? frame.contentDocument : (frame.contentWindow ? frame.contentWindow.document : frame.document);
       }
       var setFrameContent = function(hash) {
         var d = frame_doc();
         d.open();
         d.write('<div id="hash">' +
             hash.replace('&', '&amp;').replace('"', '&quot;').replace('>', '&gt;').replace('<', '&lt;') +
           '</div>'
         );
         d.close();
       }
       var forceLoad = false;
       var order = null;

       //_t.frameLoading = false;
       _t.enabled = false;
       _t.useCache = true;
       _t.onLoad = {};
       _t.cache = {};
       _t.preloads = {};

       var setHash = function(hash){
         hash = hash.replace("#","");
         if(location.hash != "#" + hash){
           location.hash = "#" + hash;
           if(browser.msie && !browser.msie8){
    //         frame.src = 'blank.html?ahHash='+encodeURIComponent(hash);

             if (browser.msie && !browser.msie8) {// added
               setFrameContent(hash);
             }
             handler();
           }
         }
         return true;
       };
       var getHash = function(){
         if(!browser.msie || browser.msie8)return location.hash.replace("#","");
         try{
           return frame_doc().getElementById('hash').innerHTML.replace(/&lt;/ig, '<').replace(/&gt;/ig, '>').replace(/&quot;/ig, '"').replace(/&amp;/ig, '&');
         }catch(e){return curHash;}
       };
       var splitHash = function(hash){
         if(!hash)return {};
         hash = hash.split("/");
         if(hash.length == 1){
           if(!_t.onLoad['default'])return {};
           if(_t.onLoad['default'].show)hash[0] = _t.onLoad['default'].show.from(hash[0]);
           return {'default':sortParams(hash[0])};
         }
         var parsed = {};
         for(var i=0;i<hash.length;i+=2){
           var h = hash[i];var p = hash[i+1];
           if(_t.onLoad[h].show){p = sortParams(_t.onLoad[h].show.from(p));}
           else{
             p = sortParams(p);
             if(!p && _t.onLoad[h])p = sortParams(_t.onLoad[h].def);
           }
           parsed[h] = p;
         }
         return parsed;
       };
       var joinHash = function(hash){
         var joined = [];
         var def = true;
         for(var i in hash){
           def = def && (i=='default');
           var p = sortParams(hash[i]);
           if(_t.onLoad[i].show){
             var p1 = _t.onLoad[i].show.to(splitParams(hash[i]));
             if(p1)p = p1;
           }
           joined.push(i + "/" + p);
         }
         if(def && joined[0])return joined[0].split("/")[1];
         return joined.sort().join("/");
       };
       var splitParams = function(params){
         if(!params)return {};
         if(typeof(params)!='string')return params;
         if(!/&|=/.test(params))return params;
         var vals = params.split("&");
         var p = {};
         for(var i=0;i<vals.length;i++){
           var v = vals[i].split("=");
           p[v[0]] = v[1];
         }
         return p;
       };
       var sortParams = function(params){
         if(typeof(params)=='number')return params+'';
         if(typeof(params)!='string'){
           params = ajx2q(params);
         }
         return params.split("&").sort().join("&");
       };

      var handler = function(){
        var origHash = getHash();
        if(origHash==curHash && !forceLoad)return;
        var state = splitHash(origHash);
        var hash = joinHash(state);
        if(hash != curHash || forceLoad){
          curHash = hash;
          var ordered = order || _t.onLoad;
          for(var i in ordered){
            if(order)i = ordered[i];
            var l = _t.onLoad[i];
            var p = state[i] || sortParams(l.def);
            if (curHash != l.ignoreHash && (p != curHashes[i] || i == forceLoad)) {
              var addAuto = !forceLoad ? '&auto=1' : '';
              forceLoad = false;
              if(l.before && !l.before(splitParams(p))){
                curHashes[i] = p;
                continue;
              }
              if (!_t.cache[i]) _t.cache[i] = {};
              if (!_t.preloads[i]) _t.preloads[i] = {};
              var p_good = decodeURIComponent(p);
              if (!_t.useCache || (!_t.cache[i][p] && !_t.cache[i][p_good])) {
                if (_t.preloads[i][p]) {
                  if (l.done) _t.preloads[i][p] = l.done;
                } else if (_t.preloads[i][p_good]) {
                  if (l.done) _t.preloads[i][p_good] = l.done;
                } else {
                  _t.getData(l,i,p + addAuto,hash);
                }
              } else if (l.done) {
                if (_t.cache[i][p]) {
                  l.done({}, _t.cache[i][p]);
                } else {
                  l.done({}, _t.cache[i][p_good]);
                }
              }
              curHashes[i] = p;
            }
          }
          if (browser.msie && !browser.msie8) {
            if(location.hash!='#' + curHash)
              location.hash = '#' + curHash;
          }
        }
      };

      var inited = false;
     _t.init = function(){
       if(!this.enabled || inited)return;
       inited = true;
       for(var i in _t.onLoad){
         var p = sortParams(_t.onLoad[i].def);
         curHashes[i] = p;
       };
       if (browser.msie && !browser.msie8){
    //     var initHash = encodeURIComponent(location.hash);
         frame = document.createElement('iframe');
         frame.style.position = 'absolute';
         frame.style.visibility  = 'hidden';
         frame.id = 'ahFrame';
         addEvent(frame, 'readystatechange', function() {
           if (this.contentWindow.document.readyState != 'complete') {
             return;
           }
           handler();
         });
    //     frame.src = "/blank.html?ahHash=" + initHash;
         document.body.appendChild(frame);
         setFrameContent(location.hash.replace('#', '')); //added
         handler();
       } else {
         setInterval(handler,150);
       }
     };
     _t.go = function(s, params){
       if(params===undefined){params = s; s = 'default';}
       var state = splitHash(curHash);
       state[s] = sortParams(params);
       var hash = joinHash(state);
       setHash(hash);
       forceLoad = s;
     };
     _t.getData = function(loadObj, id, params, hash){
       var a = new Ajax(
       (function(l,i,p,t){return function(res,text){
         if(l.done)l.done(res,text);
         if (t.useCache) {
           var autoMarker = p.indexOf('&auto=1');
           if (autoMarker != -1) {
             p = p.substr(0, autoMarker);
           }
           _t.cache[i][p] = text;
         }
       };})(loadObj,id,params, _t),
       (function(l,i,p,t){return function(res,text){
         if(l.fail)l.fail(res,text);
       };})(loadObj,id,params, _t),
       true);
       a.post(loadObj.url, params );
     };
     _t.prepare = function(id, params){
       _t.enabled = true;
       if(params===undefined){params = id; id = 'default';}
       _t.onLoad[id] = params;
     };
     _t.validateHash = function(hash){return joinHash(splitHash(hash));};
     _t.clearCache = function(id){_t.cache[id] = {}};
     _t.setHash = function(s, hash){
      if(hash===undefined){hash = s; s = 'default';}
       hash = hash.replace("#","");
       if(location.hash != "#" + hash){
         location.hash = "#" + hash;
         curHash = hash;
         curHashes[s] = curHash;
       }
     };
    // Functions below work only with one - 'default' - id.
     _t.addToCache = function(hash, text) {
       if (!_t.useCache) return;
       var id = 'default';
       var state = splitHash(hash);
       if (!_t.cache[id]) _t.cache[id] = {};
       else if (_t.cache[id][state[id]]) return;
       _t.cache[id][state[id]] = text;
     };
     _t.preLoad = function(hash, on_preloaded) {
       if (!_t.useCache) return;

       var id = 'default';
       var state = splitHash(hash);

       if (!_t.cache[id]) _t.cache[id] = {};
       if (_t.cache[id][state[id]]) return;

       if (!_t.preloads[id]) _t.preloads[id] = {};
       _t.preloads[id][state[id]] = '<loading>';

       var a = new Ajax(
       (function(i,p){return function(res,text){
         if (_t.preloads[i][p] != '<loading>') {
           _t.preloads[i][p](res, text);
         } else if (on_preloaded) {
           on_preloaded(res, text);
         }
         _t.cache[i][p] = text;
       };})(id, state[id]),
       function() {}, true);
       a.post(_t.onLoad[id].url, state[id] + '&preload=1');
     }
    }
)();

onDomReady(function() {
  ajaxHistory.init();
  var qq = ge('qquery');
  if(browser.iphone && qq){
    qq.innerHTML = '<form onsubmit="friendFilter({keyCode:13}); return false;">' + qq.innerHTML + '</form>';
  }
});

