var xmlHttpp = [];

function screenSize() {
  var w, h;
  w = (window.innerWidth ? window.innerWidth : (document.documentElement.clientWidth ? document.documentElement.clientWidth : document.body.offsetWidth));
  h = (window.innerHeight ? window.innerHeight : (document.documentElement.clientHeight ? document.documentElement.clientHeight : document.body.offsetHeight));
  return {w:w, h:h};
}

function endingsForm(n, form1, form2, form5) {
  var last_digit = n % 10;
  var last_two_digits = n % 100;

  if(last_digit == 1 && last_two_digits != 11) {
    return form1;
  }
  if((last_digit == 2 && last_two_digits != 12) || (last_digit == 3 && last_two_digits != 13) || (last_digit == 4 && last_two_digits != 14)) {
    return form2;
  }
  return form5
}

/**
 * Function : dump()
 * Arguments: The data - array,hash(associative array),object
 *    The level - OPTIONAL
 * Returns  : The textual representation of the array.
 * This function was inspired by the print_r function of PHP.
 * This will accept some data as the argument and return a
 * text that will be a more readable version of the
 * array/hash/object that is given.
 * Docs: http://www.openjs.com/scripts/others/dump_function_php_print_r.php
 */
function dump(arr,level) {
  var dumped_text = "";
  if(!level) level = 0;

  //The padding given at the beginning of the line.
  var level_padding = "";
  for(var j=0;j<level+1;j++) level_padding += "    ";

  if(typeof(arr) == 'object') { //Array/Hashes/Objects
    for(var item in arr) {
      var value = arr[item];

      if(typeof(value) == 'object') { //If it is an array,
        dumped_text += level_padding + "'" + item + "' ...\n";
        dumped_text += dump(value,level+1);
      } else {
        dumped_text += level_padding + "'" + item + "' => \"" + value + "\"\n";
      }
    }
  } else { //Stings/Chars/Numbers etc.
    dumped_text = "===>"+arr+"<===("+typeof(arr)+")";
  }
  return dumped_text;
}

 /*
 Загрузить HTML в контейнер
*/
function ajaxLoad(url,iid,params){
  xmlHttpp[iid]=GetXmlHttpObject1()
  if (xmlHttpp[iid]==null){
	alert ("Browser does not support HTTP Request")
	return
	}
  //document.getElementById(iid).innerHTML="<img src='./i/loading2.gif' />";
  //var url="./ajax/"+func+".php"

  xmlHttpp[iid].open("POST",url,true);
  xmlHttpp[iid].onreadystatechange=function() {
	  var container = null;
	  if (xmlHttpp[iid].readyState==4 || xmlHttpp[iid].readyState=="complete") {
		if(xmlHttpp[iid].responseText.indexOf('<!--CONTAINER=') == 0){
		  var  a = xmlHttpp[iid].responseText.indexOf('-->');
		  if(a >= 0){
			var b = xmlHttpp[iid].responseText.substr(14,a-14)
			if(document.getElementById(b) != undefined){
			  container = document.getElementById(b);
			} else{
			  throw "Указаный в редиректе контейнер не найден";
			}
		  }
		}else{
		  container = document.getElementById(iid);
		}
		//container.innerHTML = xmlHttpp[iid].responseText;

		$('#'+container.id).html(xmlHttpp[iid].responseText);
		scripts = container.getElementsByTagName('script');
		var loadJS = null;
		for(var i = 0; i < scripts.length; i++){
		  if(scripts[i].id == ''){ // нет ID просто EVAL
			eval(scripts[i].text);
		  }else{ // пробуем встраивать
			scriptId   = scripts[i].id;
			scripts[i].id = '';
			if(!document.getElementById(scriptId)){ // не загружен - встраиваем!
			  loadJS = document.createElement("script");
			  loadJS.setAttribute("type","text/javascript");
			  loadJS.setAttribute("id",scriptId);
			  loadJS.text = scripts[i].text;
			  document.getElementsByTagName('head')[0].appendChild(loadJS);
			}
			scripts[i].parentNode.removeChild(scripts[i]);
			i--;
		  } // попытка встраивания
		} // for  по коллекции скриптов
		// Вызываем своё событие
		$(window).trigger('ajaxLoadComplete');
	  }
  }
  xmlHttpp[iid].setRequestHeader("Accept-Charset", "windows-1251");
  xmlHttpp[iid].setRequestHeader("Accept-Language","ru, en");
  xmlHttpp[iid].setRequestHeader("Content-Type","application/x-www-form-urlencoded");
  xmlHttpp[iid].setRequestHeader("Connection", "close");
  var tmp = '';
  for(var i in params){
	 tmp+='&'+i+'='+encodeURIComponent(params[i]);
  }
  tmp = 'ajax_mode=load&ajax_target='+iid+tmp;
  xmlHttpp[iid].send(tmp);
}

function GetXmlHttpObject1(){
  var xmlHttp1=null;
  try {
   // Firefox, Opera 8.0+, Safari
	xmlHttp1=new XMLHttpRequest();
  }catch(e){
   //Internet Explorer
	try {
	  xmlHttp1=new ActiveXObject("Msxml2.XMLHTTP");
	}catch(e){
	  xmlHttp1=new ActiveXObject("Microsoft.XMLHTTP");
	}
  }
  return xmlHttp1;
}

appearance = {
  info: function(){
    $('div#appearance_out').text('info');
  },

  drop: function(){
    $('div#appearance_out').text('drop');
  },

  use: function(){
    $('div#appearance_out').text('use');
  },

  error: function(){
    $('div#appearance_out').text('error');
  }
}

core = {

  grabLogin: null,

  _findGrabLogin: function(input) {
    var tmp = null;
    if('string' == typeof input) {
      tmp = $('#'+input);
    } else if(input instanceof $) {
      tmp = input;
    } else if(input.tagName == 'INPUT' && input.type == 'text') {
      tmp = $(input);
    }
    if(!(tmp instanceof $) || tmp.length < 1) {
      alert('ОШИБКА! Неизвестный параметр core._findGrabLogin ['+input+']');
      return null;
    }
    return tmp.get(0);
  },

  setGrabLogin: function(input){
    var tmp = this._findGrabLogin(input);
    this.clearGrabLogin();
    this.grabLogin = tmp;
    return $(tmp).addClass('grabLogin').select();
  },

  clearGrabLogin: function(){
    $('input.grabLogin').removeClass('grabLogin');
    this.grabLogin = null;
  },

  toggleGrabLogin: function(input){
    var tmp = this._findGrabLogin(input);
    if($(tmp).hasClass('grabLogin')){
      this.clearGrabLogin();
    }else{
      this.setGrabLogin(tmp);
    }
  },

  refresh: function(){
    document.location = document.location;
  }

}

function str_replace ( search, replace, subject ) {
	if(!(replace instanceof Array)){
		replace=new Array(replace);
		if(search instanceof Array){
			while(search.length>replace.length){
				replace[replace.length]=replace[0];
			}
		}
	}

	if(!(search instanceof Array))search=new Array(search);
	while(search.length>replace.length){
		replace[replace.length]='';
	}

	if(subject instanceof Array){
		for(k in subject){
			subject[k]=str_replace(search,replace,subject[k]);
		}
		return subject;
	}

	for(var k=0; k<search.length; k++){
		var i = subject.indexOf(search[k]);
		while(i>-1){
			subject = subject.replace(search[k], replace[k]);
			i = subject.indexOf(search[k],i);
		}
	}
	return subject;
}


(function ($) {
$.fn.vAlign = function() {
	return this.each(function(i){
	var ah = $(this).height();
	var ph = $(this).parent().height();
	var mh = (ph - ah) / 2;
	$(this).css('margin-top', mh);
	});
};
})(jQuery);
// GENERATE UNIQUE ID DOM-ELEMENTS
(function($) {
  $.fn.genId = function(prefix,params){
    return this.each(function(){
      var counter = 0;
      var id;
      do{
        id = (prefix ? prefix + '-' : '_') + (counter++);
      }while(document.getElementById(id));
      $(this).attr('id', id);
      return this;
    });
  };
})(jQuery);