﻿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.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};
}

// get absolute coords for element el
Ys.getAbsolutePos = function(el){
	var r = { x: el.offsetLeft, y: el.offsetTop };
	if (el.offsetParent){
		var tmp = 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){
	var obj = document.getElementById(id);
	if(typeof obj == 'object'){
		var scroll_val = getAbsolutePos(obj);
		var scroll = getPageScroll();
		scrollInterval = window.setInterval('jumpToAction({scroll_val: '+(scroll_val.y)+', start_scroll: '+(scroll.top)+', step: 20, speed: 4})', 30);
	}
}

Ys.jumpToAction = function(config){
	var scroll = getPageScroll();
	var step = config.step;
	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){
		window.clearInterval(scrollInterval);
		scrollInterval = '';
	}
	window.scrollTo(0, scroll.top + step);
}

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);
	if((v >= 11 && v <= 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();
            }
        }
    };
}();
