Ext.namespace('Ys');

Ext.BLANK_IMAGE_URL = '/i/px.gif';

// форматирует вывод числа, аналог number_format() в PHP
Ys.number_format = function (number, decimals, dec_point, thousands_sep){
	if(Ext.isEmpty(number)) return '';
	var exponent = "";
	var numberstr = number.toString ();
	var eindex = numberstr.indexOf ("e");
	var i, z;
	if(eindex > -1){
		exponent = numberstr.substring (eindex);
		number = parseFloat (numberstr.substring (0, eindex));
	}
	
	if(decimals != null){
		var temp = Math.pow (10, decimals);
		number = Math.round (number * temp) / temp;
	}
	var sign = number < 0 ? "-" : "";
	var integer = (number > 0 ? 
			Math.floor (number) : Math.abs (Math.ceil (number))).toString ();
	
	var fractional = number.toString ().substring (integer.length + sign.length);
	dec_point = dec_point != null ? dec_point : ".";
	fractional = decimals != null && decimals > 0 || fractional.length > 1 ? (dec_point + fractional.substring (1)) : "";
	if(decimals != null && decimals > 0){
		for(i = fractional.length - 1, z = decimals; i < z; ++i)
			fractional += "0";
	}
	
	thousands_sep = (thousands_sep != dec_point || fractional.length == 0) ? 
									thousands_sep : null;
	if(thousands_sep != null && thousands_sep != ""){
		for (i = integer.length - 3; i > 0; i -= 3)
			integer = integer.substring (0 , i) + thousands_sep + integer.substring (i);
	}
	return sign + integer + fractional + exponent;
}

// http://www.artlebedev.ru/tools/technogrette/js/validate_xml_value/
// correct: http://forum.hitech.by/topic148.html
Ys.xmlValidate = function( sValue ){
	if( sValue ){
			// вырезаем инструкции
			sValue = sValue.replace( /<\?.*\?>/g, '' );
			// вырезаем doctype
			sValue = sValue.replace( /<\!DOCTYPE.*?>/g, '' );
			// вырезаем коменты и CDATA
			var rTags = /(<!--.*?-->|<\!\[CDATA\[.*?\]\]>)/g;
			while( sValue.search( rTags ) >= 0 ){
					sValue = sValue.replace( rTags, '' );
			}
			// вырезаем одинарные тэги
			sValue = sValue.replace( /<[-\w:]+(\s+[-\w:]+\s*=\s*"[^<>]*?")*\s*\/>([^<]*)/gi, '' );
			// вырезаем двойные тэги
			var rTags = /<([-\w:]+)(\s+[-\w:]+\s*=\s*"[^<>]*?")*\s*>[^<>]*?<\/\1>([^<]*)/g;
			while( sValue.search( rTags ) >= 0 ){
					sValue = sValue.replace( rTags, '' );
			}
			if( sValue.search( /[<>]/ ) >= 0 || sValue.search( /&(?!(\w+;|#\d+;))/ ) >= 0 ){
					//alert( sValue )// можно показать sValue;
					return false;
			}
			return true;
	}else{
			return true;
	}
}

// предзагрузка картинок. жрет массив с путями
Ys.preloadImgs = function(imgs){
	var pre;
	for(var i = 0; i < imgs.length; i++){
		pre = new Image();
		pre.src = imgs[i];
	}
}

Ys.getElementsByNameIE = function(tag, name){
	return Ext.DomQuery.jsSelect(tag+'[name='+name+']');
	/*var elem = document.getElementsByTagName(tag);
	var arr = new Array();
	for(i = 0, iarr = 0; i < elem.length; i++){
		att = elem[i].getAttribute("name");
		if(att == name){
			arr[iarr] = elem[i];
			iarr++;
		}
	}
	return arr;*/
}

// cancel event, multybrowsing
Ys.cancelDefaultEvent = function(e){
	if(e.preventDefault)
		e.preventDefault();
	else
		e.returnValue= false;
	return false;
}

Ys.getPageScroll = function(){
	/* scrollLeft: The distance between the horizontal scrollbar 
		with the left edge of the frame.
		scrollTop:  The distance between the vertical scrollbar
		with the top edge of the frame. 

		Get the scroll value from different browsers.
		Determine the browser type first. 
		And then get the value from the particular property.*/
	var scrollLeft, scrollTop;

	if(window.pageXOffset)
		scrollLeft = window.pageXOffset 
	else if(document.documentElement && document.documentElement.scrollLeft)
		scrollLeft = document.documentElement.scrollLeft; 
	else if(document.body)
		scrollLeft = document.body.scrollLeft; 

	if(window.pageYOffset)
		scrollTop = window.pageYOffset 
	else if(document.documentElement && document.documentElement.scrollTop)
		scrollTop = document.documentElement.scrollTop; 
	else if(document.body)
		scrollTop = document.body.scrollTop; 

	return {"left":scrollLeft, "top":scrollTop};
}

Ys.getVisibleArea = function(){
	var windowWidth, windowHeight;
	if(window.innerWidth)// Safari, Opera, FF
		windowWidth = window.innerWidth;
	else if(document.documentElement && document.documentElement.clientWidth)// IE
		windowWidth = document.documentElement.clientWidth;
	else if(document.body)
		windowWidth = document.body.offsetWidth;
	
	if(window.innerHeight)
		windowHeight = window.innerHeight;
	else if(document.documentElement && document.documentElement.clientHeight)
		windowHeight = document.documentElement.clientHeight;
	else if(document.body)
		windowHeight = document.body.clientHeight;
	return {"width":windowWidth, "height":windowHeight};
}

Ys.getDocumentArea = function(){
	var width, height;
	width = document.documentElement.clientWidth; // FF, Safari, IE
	if(width < document.body.scrollWidth) // Opera
		width = document.body.scrollWidth;
	height = document.documentElement.clientHeight; // FF, Safari, IE
	if(height < document.body.scrollHeight) // Opera
		height = document.body.scrollHeight;
	//document.getElementById('debug').innerHTML += '<br />'+'getDocumentArea.width='+width+' getDocumentArea.height='+height;
	return {'width':width, 'height':height}
}


// type = [error|success]
Ys.showProcessingMsg = function(text, type, coords){
	if(type === undefined || !type)	type = 'success';
	if(coords === undefined || !coords)	coords = {x:200,y:200};
	if(type == 'success')	var style = "background: yellow; color: black; border: 1px solid #999999;";
	else if(type == 'error') var style = "background: #FFAFAF; color: black; border: 1px solid #8F1111;";
	var msgDiv = document.createElement('div');
	var pageScroll = Ys.getPageScroll();
	msgDiv.setAttribute('style', "position: absolute; top: "+(coords.y+pageScroll.top)+'px'+"; left: "+(coords.x+pageScroll.left)+'px'+"; width: 200px; height: 50px; padding: 6px; "+style);
	var oMsgDiv = document.body.appendChild(msgDiv);
	oMsgDiv.innerHTML = text;
	window.setTimeout(Ys.closeProcessingMsg, (type == 'error'?100000:10000), oMsgDiv);
}

Ys.closeProcessingMsg = function(oMsgDiv){
	document.body.removeChild(oMsgDiv);
}

// get absolute coords for element el
Ys.getAbsolutePos = function(el){
	var r = { x: el.offsetLeft, y: el.offsetTop };
	if (el.offsetParent){
		var tmp = Ys.getAbsolutePos(el.offsetParent);
		r.x += tmp.x;
		r.y += tmp.y;
	}
	return r;
}

// show debugging window in browser page
Ys.debug = function(params){
	var html = params.html; // content to add to debug window
	var clean = params.clean; // [true] - clean innerHTML
	var cr = params.cr; // [true] - CR, new line
	
	var oDebug = document.getElementById('x-debug');
	if(oDebug === undefined || !oDebug){
		var visArea = Ys.getVisibleArea();
		oDebug = document.createElement('div');
		oDebug.id = 'x-debug';
		oDebug.style.position = 'fixed';
		oDebug.style.top = '100px';
		oDebug.style.right = '50px';
		oDebug.style.width = '300px';
		oDebug.style.height = (visArea.height - 200)+'px';
		oDebug.style.backgroundColor = '#FFEE9F';
		oDebug.style.border = '1px solid #8F7911';
		oDebug.style.overflow = 'scroll';
		oDebug = document.body.appendChild(oDebug);
	}
	if(typeof params == 'string' || typeof params == 'number' || (typeof params == 'object' && params.html === undefined)){
		html = String(params);
		if(oDebug.innerHTML != '') cr = true;
	}	else if(typeof params == 'object'){
		html = params.html;
		clean = params.clean;
	}
	if(clean !== undefined && clean === true) oDebug.innerHTML = '';
	oDebug.innerHTML += (cr?'<br />':'')+(html);
}

Ys.jumpTo = function(id){
	if(window.scrollMaxY === undefined)
		window.scrollMaxY = document.documentElement.scrollHeight - document.documentElement.clientHeight;
	var obj = document.getElementById(id);
	if(typeof obj == 'object'){
		var mode;
		var scroll_val = Ys.getAbsolutePos(obj);
		var scroll = Ys.getPageScroll();
		if(scroll.top == scroll_val.y)
			return false;
		else{
			if(scroll.top < scroll_val.y)
				mode = 'd'; // down scroll
			else
				mode = 'u'; // up scroll
			window.scrollInterval = window.setInterval('Ys.jumpToAction({scroll_val: '+(scroll_val.y)+', start_scroll: '+(scroll.top)+', step: 20, speed: 4, mode: "'+mode+'"})', 30); // 30
		}
	}
}

Ys.clearJumpTo = function(){
	if(window.scrollInterval && !Ext.isEmpty(window.scrollInterval)){
		window.clearInterval(window.scrollInterval);
		window.scrollInterval = '';
	}
}

Ys.jumpToAction = function(config){
	var scroll = Ys.getPageScroll();
	var step = config.step;
	
	if(config.mode == 'd') {
		if((scroll.top > config.start_scroll + 0) && (scroll.top + config.step < config.scroll_val - 100))
			step = config.step * config.speed;
		if(scroll.top + step >= config.scroll_val || scroll.top == window.scrollMaxY) {
			Ys.clearJumpTo();
		}
		else {
			if(scroll.top + step >= window.scrollMaxY) {
				step = window.scrollMaxY - scroll.top;
			}
			window.scrollTo(0, scroll.top + step);
		}
	}
	else if(config.mode == 'u') {
		if((scroll.top < config.start_scroll + 0) && (scroll.top + config.step > config.scroll_val + 100))
			step = config.step * config.speed;
		if(scroll.top + step <= config.scroll_val || scroll.top == 0) {
			Ys.clearJumpTo();
		}
		else {
			window.scrollTo(0, scroll.top - step);
		}
	}
	else {
		Ys.clearJumpTo();
	}
}

Ys.getCookie = function(name){
	var cook = document.cookie;
	var pos = cook.indexOf(name + '=');
	if(pos == -1){
		return null;
	} else {
		var pos2 = cook.indexOf(';', pos);
		if(pos2 == -1)
			return unescape(cook.substring(pos + name.length + 1));
		else 
			return unescape(cook.substring(pos + name.length + 1, pos2));
	}
}

Ys.setCookie = function(name, value, path, domain, expires, secure){
	// set time, it's in milliseconds
	var today = new Date();
	today.setTime(today.getTime());

	/*
	if the expires variable is set, make the correct 
	expires time, the current script below will set 
	it for x number of days, to make it for hours, 
	delete * 24, for minutes, delete * 60 * 24
	*/
	if(expires){
		expires = expires * 1000 * 60 * 60 * 24;
	}
	var expires_date = new Date( today.getTime() + (expires) );

	document.cookie = name + "=" +escape( value ) +
		( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) + 
		( ( path ) ? ";path=" + path : "" ) + 
		( ( domain ) ? ";domain=" + domain : "" ) +
		( ( secure ) ? ";secure" : "" );
}

Ys.deleteCookie = function (name, path, domain) {
if (Ys.getCookie( name ) ) document.cookie = name + "=" +
( ( path ) ? ";path=" + path : "") +
( ( domain ) ? ";domain=" + domain : "" ) +
";expires=Thu, 01-Jan-1970 00:00:01 GMT";
}


/*
	возвращает корректное, русское значение для числа
	first - 1 товарная позиция,
	second - 5 товарных позиций,
	third - 3 товарные позиции
*/
Ys.humanSense = function(v, first, second, third, nothing){
	if(Ext.isEmpty(v) || v == 0) return nothing;
	var residue = (v % 10);
	var residue2 = (v % 100);
	//if((v >= 11 && v <= 14) || residue == 0 || (residue >= 5 && residue <= 9)) return second;
	if((residue2 >= 11 && residue2 <= 14) || residue == 0 || (residue >= 5 && residue <= 9)) return second;
	else if(residue == 1) return first;
	else if(residue >= 2 && residue <= 4) return third;
}

Ys.getRandomInt = function(min, max){
	return Math.floor(Math.random() * (max - min + 1)) + min;
}

Ys.lightMsg = function(){
    var msgCt;

	function createBox(t, s, width){
		return ['<div class="light-msg" style="width: '+(!Ext.isEmpty(width)?width:'250px;')+';">',
							'<div class="x-box-tl"><div class="x-box-tr"><div class="x-box-tc"></div></div></div>',
							'<div class="x-box-ml"><div class="x-box-mr"><div class="x-box-mc"><h3>', t, '</h3>', s, '</div></div></div>',
							'<div class="x-box-bl"><div class="x-box-br"><div class="x-box-bc"></div></div></div>',
						'</div>'].join('');
	}
	return {
		msg : function(title, format, ttl, width){
			if(!msgCt){
					msgCt = Ext.DomHelper.append(document.body, {id:'msg-div'}, true);
			}
			msgCt.alignTo(document, 't-t');
			var s = String.format.apply(String, Array.prototype.slice.call(arguments, 1));
			var m = Ext.DomHelper.append(msgCt, {html:createBox(title, s, width)}, true);
			if(Ext.isEmpty(ttl)) ttl = 5;
			m.slideIn('t').pause(ttl).ghost("t", {remove:true});
		},

		init : function(){
			var t = Ext.get('exttheme');
			if(!t){ // run locally?
					return;
			}
			var theme = Cookies.get('exttheme') || 'aero';
			if(theme){
					t.dom.value = theme;
					Ext.getBody().addClass('x-'+theme);
			}
			t.on('change', function(){
					Cookies.set('exttheme', t.getValue());
					setTimeout(function(){
							window.location.reload();
					}, 250);
			});

			var lb = Ext.get('lib-bar');
			if(lb){
					lb.show();
			}
		}
	};
}();

Ys.translit = function(line){
	line = Ext.util.Format.lowercase(line);
	line = line.replace(/[\s\,\(\)\=\\\/]/g, '_');
	line = line.replace(/[\'\"\@\:\#\$\%\&\!\?\*]/g, '');
	//line = line.replace('.', '');
	line = line.replace(/\+/g, 'plus_');
	line = line.replace('__', '_');
	line = line.replace(/а/g, 'a');
	line = line.replace(/б/g, 'b');
	line = line.replace(/в/g, 'w');
	line = line.replace(/г/g, 'g');
	line = line.replace(/д/g, 'd');
	line = line.replace(/е/g, 'e');
	line = line.replace(/ё/g, 'e');
	line = line.replace(/ж/g, 'j');
	line = line.replace(/з/g, 'z');
	line = line.replace(/и/g, 'i');
	line = line.replace(/й/g, 'j');
	line = line.replace(/к/g, 'k');
	line = line.replace(/л/g, 'l');
	line = line.replace(/м/g, 'm');
	line = line.replace(/н/g, 'n');
	line = line.replace(/о/g, 'o');
	line = line.replace(/п/g, 'p');
	line = line.replace(/р/g, 'r');
	line = line.replace(/с/g, 's');
	line = line.replace(/т/g, 't');
	line = line.replace(/у/g, 'y');
	line = line.replace(/ф/g, 'f');
	line = line.replace(/х/g, 'x');
	line = line.replace(/ц/g, 'c');
	line = line.replace(/ч/g, 'ch');
	line = line.replace(/ш/g, 'sh');
	line = line.replace(/щ/g, 'sh');
	line = line.replace(/ь/g, '');
	line = line.replace(/ы/g, 'i');
	line = line.replace(/ъ/g, '');
	line = line.replace(/э/g, 'e');
	line = line.replace(/ю/g, 'u');
	line = line.replace(/я/g, 'ya');
	line = line.replace(/А/g, 'a');
	line = line.replace(/Б/g, 'b');
	line = line.replace(/В/g, 'w');
	line = line.replace(/Г/g, 'g');
	line = line.replace(/Д/g, 'd');
	line = line.replace(/Е/g, 'e');
	line = line.replace(/Ё/g, 'e');
	line = line.replace(/Ж/g, 'j');
	line = line.replace(/З/g, 'z');
	line = line.replace(/И/g, 'i');
	line = line.replace(/Й/g, 'j');
	line = line.replace(/К/g, 'k');
	line = line.replace(/Л/g, 'l');
	line = line.replace(/М/g, 'm');
	line = line.replace(/Н/g, 'n');
	line = line.replace(/О/g, 'o');
	line = line.replace(/П/g, 'p');
	line = line.replace(/Р/g, 'r');
	line = line.replace(/С/g, 's');
	line = line.replace(/Т/g, 't');
	line = line.replace(/У/g, 'y');
	line = line.replace(/Ф/g, 'f');
	line = line.replace(/Х/g, 'x');
	line = line.replace(/Ц/g, 'c');
	line = line.replace(/Ч/g, 'ch');
	line = line.replace(/Ш/g, 'sh');
	line = line.replace(/Щ/g, 'sh');
	line = line.replace(/Ь/g, '');
	line = line.replace(/Ы/g, 'i');
	line = line.replace(/Ъ/g, '');
	line = line.replace(/Э/g, 'e');
	line = line.replace(/Ю/g, 'u');
	line = line.replace(/Я/g, 'ya');
	return line;
}


function insertAtCursor(myField, myValue)
{
	//IE support
	if (document.selection) {
		myField.focus();
		sel = document.selection.createRange();
		sel.text = myValue;
	}

	//MOZILLA/NETSCAPE support
	else if (myField.selectionStart || myField.selectionStart == '0') {
		var startPos = myField.selectionStart;
		var endPos = myField.selectionEnd;
		restoreTop = myField.scrollTop;
		myField.value = myField.value.substring(0, startPos) + myValue + myField.value.substring(endPos, myField.value.length);
		myField.selectionStart = startPos + myValue.length;
		myField.selectionEnd = startPos + myValue.length;

		if (restoreTop > 0) {
			myField.scrollTop = restoreTop;
		}
	}
	else {
		myField.value += myValue;
	}
}

Ys.insertAtCursor = insertAtCursor;


