var include = {
    js : function(filename){
    	var head = document.getElementsByTagName('head').item(0);
		script = document.createElement('script');
		script.src = filename;
		script.type = 'text/javascript';
		head.appendChild(script);
    },
    div : function(div_name,class_name,display){
	    var body = document.getElementsByTagName('body').item(0);
	    div = document.createElement('div');
	    body.appendChild(div);
	    div.id = div_name;
	    div.className = class_name;
	    div.style.display = display;
    },
    css : function(filename){
    	var head = document.getElementsByTagName('head').item(0);
		link = document.createElement('link');
		link.href = filename;
		link.rel = 'stylesheet';
		head.appendChild(link);
    }
}

Abs = {
	extend : function(subclass, superclass)
	{
		function Dummy(){}
		Dummy.prototype = superclass.prototype;
		subclass.prototype = new Dummy();
		subclass.superclass = superclass;
		for(var property in superclass){
			subclass[property] = superclass[property];
    	}
	}
};

/* ================== INPUT RADIO HANDLER ========================== */
var radioHandler = {
    radioObj : null,
    init : function(id){
    	this.radioObj = $("#"+id).getElementsByTagName('input');
    },
	get : function(id){
		//alert($("#"+id+" input:radio:checked").length);
		$("#"+id+" input:radio:checked").each(function(i){
			var ch = $(this).val();
			if($(this).checked == true){
				return ch;
			}	
		});
	},
	check : function(id,value){
		$("#"+id+" input:radio").each(function(){
			$(this).attr("checked","");
			if($(this).val() == value){
				$(this).attr("checked", "checked");
			}
		});
	},
	
	disableAll : function(id){
		this.init(id);
		for(var i = 0; i < this.radioObj.length; i++){ 
			this.radioObj[i].disabled = true;
 		}
	},
	enableAll : function(id){
		this.init(id);
		for(var i = 0; i < this.radioObj.length; i++){ 
			this.radioObj[i].disabled = false;
 		}
	}
}
/* ==== END ========= INPUT RADIO HANDLER ========================== */


/* ================== INPUT SELECT HANDLER ========================= */
var selectHandler = {
	set : function(id,value){
		$("#"+id+" option").each(function(){
			if($(this).val() == value){
				$(this).attr('selected','selected');
			}
		});
	},
	getById : function(id){
		return $("#"+id+" option:selected").val();
	}	
}
/* ==== END ========= INPUT SELECT HANDLER ========================= */

/* ================== INPUT CHECBOXES HANDLER ========================= */
var checkboxHandler = {
    checkboxObj : null,
    init : function(id){
    	this.checkboxObj = $("#"+id+" :input");
    },
    checkAll : function(id){
    	this.init(id);
    	//alert(this.checkboxObj.length);
    	for(var i = 0; i < this.checkboxObj.length; i++){
    		this.checkboxObj[i].checked = true;
    	} 
    },
    uncheckAll : function(id){
    	this.init(id);
    	for(var i = 0; i < this.checkboxObj.length; i++)
    		this.checkboxObj[i].checked = false;
    },
    disableAll : function(id){
    	this.init(id);
    	for(var i = 0; i < this.checkboxObj.length; i++)
    		this.checkboxObj[i].disabled = true;
    },
    enableAll : function(id){
    	this.init(id);
    	for(var i = 0; i < this.checkboxObj.length; i++)
    		this.checkboxObj[i].disabled = false;
    },
	getSelectedString : function(id){
     	this.init(id);
     	var arr = new Array();
     	for(var i = 0; i < this.checkboxObj.length; i++){ 
			if(this.checkboxObj[i].checked == true)
				arr.push(this.checkboxObj[i].value);
 		}
 		if(arr)
 			return arr.join(',');
 		return false;
	},
	setSelectedString : function(id,str){
     	this.init(id);
     	this.uncheckAll(id);
     	//var arr = new Array();
     	var strArr = str.split(',');
     	for(var i = 0; i < this.checkboxObj.length; i++){ 
			//alert('анализ чекбокса: ' + this.checkboxObj[i].value);
			for(var j = 0; j < strArr.length; j++){
				//alert('анализ чекбокса: ' + this.checkboxObj[i].value + ' анализ строки: '+strArr[j]);
				if(this.checkboxObj[i].value == strArr[j]){ 
					//alert(this.checkboxObj[i].value +' = '+ strArr[j]);
					this.checkboxObj[i].checked = true;
				}
			}
 		}
	}
}
/* ==== END ========= INPUT CHECBOXES HANDLER ========================= */

// ======================== COOKIE handler functions ==============================
// === 1. function Get_Cookie - return Cookie by name =============================
// === 2. function Set_Cookie - set cookie ========================================

function Get_Cookie(name){ 
 	var start = document.cookie.indexOf(name+"="); 
 	var len = start+name.length+1; 
 	if ((!start) && (name != document.cookie.substring(0,name.length))) 
	return null; 
	if (start == -1) 
		return null; 
	var end = document.cookie.indexOf(";",len); 
	if (end == -1) 
		end = document.cookie.length; 
	return unescape(document.cookie.substring(len,end)); 
} 

// This function has been slightly modified
function Set_Cookie(name,value,expires,path,domain,secure) { 
	expires = expires * 60*60*24*1000;
	var today = new Date();
	var expires_date = new Date( today.getTime() + (expires) );
	var cookieString = name + "=" +escape(value) + 
		( (expires) ? ";expires=" + expires_date.toGMTString() : "") + 
		( (path) ? ";path=" + path : "") + 
		( (domain) ? ";domain=" + domain : "") + 
		( (secure) ? ";secure" : ""); 
	document.cookie = cookieString; 
} 


var windowSize = {
	getWindowSize: function(doc) {
    	//alert('getWindowSize');
    	doc = doc || document;
    	var win_w, win_h;
    	if (self.innerHeight) {
    		win_w = self.innerWidth;
            win_h = self.innerHeight;
        } 
        else if (doc.documentElement && doc.documentElement.clientHeight) {
            win_w = doc.documentElement.clientWidth;
            win_h = doc.documentElement.clientHeight;
        }
        else if (doc.body) {
            win_w = doc.body.clientWidth;
            win_h = doc.body.clientHeight;
        }
       // alert('win_w = '+win_w);
        this.winWidth = win_w;
        this.winHeight = win_h;
    },
    _width: function(){
    	//alert('_width');
    	this.getWindowSize();
    	//alert('return winWidth = '+this.winWidth);
    	return this.winWidth;
    },
    _height: function(){
    	this.getWindowSize();
    	return this.winHeight;
    }
}



var JsPopupWin = {
	interval : '200',
	scrollTop: null, // scrolloing position
	width: null, //inner win width
	height: null, // inner win height
	init : function(width,height,bgColor,winColor,borderColor,alfa,inner,content,bodyWidth){
		this.active = true;
		this.height = height;
		this.width = width;
		// create structure
		include.div('popup_ext','popup_ext','');
		$('#popup_ext').css({
			position:'absolute',
			width:'100%',
			height:'100%',
			zIndex:'10020',
			top:'0',
			left:'0',
			backgroundColor:bgColor,
			opacity:alfa
		});
		include.div('popup_inner','popup_inner','');
		$('#popup_inner').css({
			position:'absolute',
			zIndex:'10025',
			overflow:'visible',
			backgroundColor:winColor,
			border:'1px solid '+ borderColor,
			display: 'none'
		});
		
		var cont =	
		'<div id="popup_content" class="popup_content">'+
			'<img src="/abs/lib/absJsLib/images/loading.gif" border="0">'+
		'</div>';
		this.getWindowSize();
		if(bodyWidth) 
			this.winWidth = bodyWidth;
		this.innerLeft = (this.winWidth - this.width )/2;
		this.innerTop = (this.winHeight - this.height)/2;  
		//alert(this.innerTop);
		this.listener();
		$('#popup_inner')
			.css({width: this.width + 'px', height: this.height + 'px'})
			.html(cont);
		if(inner)
			$('#popup_inner').html( $("#"+inner).html() );
		if(content)
			$('#popup_inner').html(content);
			
		$('#popup_inner').show();
		this.adListener();
		
	},
	changeHeight : function(newHeight){
		if(newHeight)
			$('#popup_inner').css({height: newHeight + 'px'});
	},
	getScrollTop : function(documentElement){
        var t;
        if (document.documentElement && document.documentElement.scrollTop)
                t = document.documentElement.scrollTop;
        else if (document.body)
                t = document.body.scrollTop;
        return t;
 	},
 	adListener : function(){
	 	this.listener();
 	},
 	listener : function(){
 		if(this.active){
	 		var _scroll = this.getScrollTop();
	 		if(_scroll !== this.scrollTop){
	 			this.innerTop = (this.innerTop - this.scrollTop)+_scroll; 
	 			this.scrollTop = _scroll;
	 			this.popupWinPos();
	 			this.innerWinPos();
	 		}
	 		//this.adListener();
	 		this.tl = setTimeout(function(){JsPopupWin.listener()}, this.interval);
 		}
 	},
 	innerWinPos : function(){
 		//alert(this.innerTop);
 		$('#popup_inner').css({left: this.innerLeft+'px', top: this.innerTop+'px' });
 	},
 	popupWinPos : function(){
 		$('#popup_ext').css({ top: this.scrollTop });
 	},
 	getWindowSize: function(doc) {
        doc = doc || document;
        var win_w, win_h;
        if (self.innerHeight) {
            win_w = self.innerWidth;
            win_h = self.innerHeight;
        } else if (doc.documentElement && doc.documentElement.clientHeight) {
            win_w = doc.documentElement.clientWidth;
            win_h = doc.documentElement.clientHeight;
        } else if (doc.body) {
            win_w = doc.body.clientWidth;
            win_h = doc.body.clientHeight;
        }
        this.winWidth = win_w;
        this.winHeight = win_h;
    },
    close : function(){
 		//Effect.SlideUp('popup_inner');	
 		$('#popup_ext').remove();
 		$('#popup_inner').remove();
		this.active = false;
		clearTimeout(this.tl);
		this.innerTop = null;
		this.scrollTop = null;
 	}
}


var include = {
    js : function(filename){
    	var head = document.getElementsByTagName('head').item(0);
		script = document.createElement('script');
		script.src = filename;
		script.type = 'text/javascript';
		head.appendChild(script);
    },
    div : function(div_name,class_name,display){
	    var body = document.getElementsByTagName('body').item(0);
	    div = document.createElement('div');
	    body.appendChild(div);
	    div.id = div_name;
	    div.className = class_name;
	    div.style.display = display;
    },
    css : function(filename){
    	var head = document.getElementsByTagName('head').item(0);
		link = document.createElement('link');
		link.href = filename;
		link.rel = 'stylesheet';
		head.appendChild(link);
    }
}

function trim(str)
{
    if(!str || typeof str != 'string')
        return null;
    return str.replace(/^[\s]+/,'').replace(/[\s]+$/,'').replace(/[\s]{2,}/,' ');
}

function alertError(er) {
	var pattern = /&/;
	var replacement = '\n';
	for(var i = 0; i < 30; i++){
	 	er = er.replace(pattern, replacement);
	}
	alert(er);
}

function toggle(obj) {
	var el = document.getElementById(obj);
	if ( el.style.display != 'none' ) {
		el.style.display = 'none';
	}
	else {
		el.style.display = '';
	}
}

Abs.lightBox = function(options) {
	var settings = {
		borderWidth: 4,
		borderColor: '#ebebeb',
		bgColor: '#fff'
	};
	
	var service = {
		getWindowSize : function(doc){ 
			doc = doc || document;
	        var win_w, win_h;
	        if (self.innerHeight) {
	            win_w = self.innerWidth;
	            win_h = self.innerHeight;
	        } else if (doc.documentElement && doc.documentElement.clientHeight) {
	            win_w = doc.documentElement.clientWidth;
	            win_h = doc.documentElement.clientHeight;
	        } else if (doc.body) {
	            win_w = doc.body.clientWidth;
	            win_h = doc.body.clientHeight;
	        }
	    	settings.winWidth = win_w;
			settings.winHeight = win_h;
		}	
	}
	
	if(options){
		for(var property in options){
			settings[property] = options[property];
    	}
	}
	
	if(!settings.width){
		alert('Необходимо указать ширину блока');
		return;
	}
	
	if(!settings.content){
		alert('Пустое окно: отсутствует содержание');
		return;
	}
	
	$("select").hide();
	
	include.div('TB_overlay','TB_overlayBG','');
	include.div('TB_window','','');
	$("#TB_window").html(settings.content);
	service.getWindowSize();
	settings.margLeft = -settings.width/2;
	settings.margTop = -$('#TB_window').height();

	$('#TB_window').css({
		display		:	'block',
		marginLeft	:	settings.margLeft,
		marginTop	: 	settings.margTop,
		width		: 	settings.width,
		border		: 	settings.borderWidth+'px solid '+ settings.borderColor,
		background	: 	settings.bgColor
	});
}

Abs.lightBox.close = function() { 
	$('#TB_overlay').remove();
 	$('#TB_window').remove();
 	$("select").show();
}

function getrandom(min_random, max_random) {
    var range = max_random - min_random + 1;
    return Math.floor(Math.random()*range) + min_random;
}


var curDate = function(){
	var time=new Date();
	this.month = time.getMonth()+1;
	this.date = time.getDate();
	this.year = time.getYear();
	if (this.year < 2000){
		this.year = this.year + 1900;
	}
}	


var AbsDebug = {
	init : function(){
		alert('bvdfb');	
		if( !$("#debugFrame").length ){
			var winId = "debugFrame";
			document.mochaUI.newWindow({
				loadMethod: 'html',
				id: winId,
				title: 'ABSbug',
				content: '<div id="debugContent"></div>',
				width: 900,
				height: 400,
				y:getScrollTop() + 100,
				resizable: true,
				modal: false
			});
		}
	},
	addRow : function(_class,_method,_text){
		alert('addRow');
		AbsDebug.init();
		var n = $(".debugStr").length;
		$("#debugContent").append('<div class="debugStr"><b>'+(1+n)+'. </b><b>Class:</b> '+_class+'"  <b>Method:</b> '+_method+'  <b>InfoText: </b>'+_text+'</div>')
		//console.log('Class: "'+_class+'"  Method: "'+_method+'"  InfoText: "'+_text+'"');
	}
	
}

/**
 * Функция для дебага ассоциативного массива в firebug.
 * @param arr - ассоциативный массив
 * @return void
 */
function debugAssocArr(arr) {
	for( var a_name in arr ) {
		console.warn(a_name + ':' + arr[a_name]);
	}
}

/**
 * Валидация email.
 * Возвращает true если email валидный, false - в противном случае.
 * @param email - string
 * @return boolean
 */
function emailValidate(email) {
	var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
	if(reg.test(email) == false) {
		return false;
	}
	return true;
}

/**
 * Валидация строки.
 * Кирилица, латиница, цифры, дефис, нижнее подчеркивание.
 * @param str - string
 * @return boolean
 */
strValidate_1 = function(str){
	var legalChars = /^[A-Za-zА-Яа-я0-9_\-]+$/;
	if (legalChars.test(str)){
  		return true;
  	}	
	return false;	 
}

/**
 * Валидация пароля.
 * Латиница, цифры, дефис, нижнее подчеркивание.
 * @param str - string
 * @return boolean
 */
passValidate = function(str){
	var legalChars = /^[A-Za-z0-9_\-]+$/;
   	if (legalChars.test(str)){
   		return true;
   	}	
   	return false;	 
}


function call_user_func_array (cb, parameters) {
    // Call a user function which is the first parameter with the arguments contained in array  
    // 
    // version: 909.322
    // discuss at: http://phpjs.org/functions/call_user_func_array
    // +   original by: Thiago Mata (http://thiagomata.blog.com)
    // +   revised  by: Jon Hohle
    // +   improved by: Brett Zamir (http://brett-zamir.me)
    // *     example 1: call_user_func_array('isNaN', ['a']);
    // *     returns 1: true
    // *     example 2: call_user_func_array('isNaN', [1]);
    // *     returns 2: false
    var func;
    if (typeof cb == 'string') {
       // console.warn('param is string = '+cb);
		if (typeof this[cb] == 'function') {
            func = this[cb];
        } else {
            func = (new Function(null, 'return ' + cb))();
        }
    } else if (cb instanceof Array) {
        func = eval(cb[0]+"['"+cb[1]+"']");
    }
    
    if (typeof func != 'function') {
        throw new Error(func + ' is not a valid function');
    }
 
    return func.apply(null, parameters);
}

function str_replace(haystack, needle, replace) {
	temp = haystack.split(needle);
	return temp.join(replace);
}

function in_array(needle, haystack, strict) {    // Checks if a value exists in an array
    // 
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
 
    var found = false, key, strict = !!strict;
 
    for (key in haystack) {
        if ((strict && trim(haystack[key]) === needle) || (!strict && trim(haystack[key]) == needle)) {
            found = true;
            break;
        }
    }
 
    return found;
}

/**
 * Установщик опций, передаваемых в объект.
 * @param options - опции по умолчанию
 * @param extraOptions - новые опции
 * @return options - обновленный ассоциативный массив
 */
function setOptions(options,extraOptions) {
	for( var o_name in options ) {
		if (typeof extraOptions[o_name] !== "undefined"){
			options[o_name] = extraOptions[o_name];
		} 
	}
	return options;
}

function getScrollTop(documentElement){
    var t;
    if (document.documentElement && document.documentElement.scrollTop)
            t = document.documentElement.scrollTop;
    else if (document.body)
            t = document.body.scrollTop;
    return t;
}

function getScrollLeft(documentElement){
    var t;
    if (document.documentElement && document.documentElement.scrollLeft)
            t = document.documentElement.scrollLeft;
    else if (document.body)
            t = document.body.scrollLeft;
    return t;
}
