/**
* web-T::CMS JS Library 
* @version 1.5
* @author goshi
* @package javascript::share
*
* History:
* 	1.5	03.01.10/goshi	move class manipulation functions to portal.css object, remove projects functions
* 	1.4	20.10.09/goshi	add trim functions
* 	1.31	13.10.09/goshi	add get_style
* 	1.3	02.05.09/goshi	remove do_nothing function
* 	1.2	07.04.09/goshi	remove showLoader to another file
* 	1.1	21.02.09/goshi	add sbmtKeyChecker function
* 	1.0	12.09.08	
*/


function $_(objid){

	return document.getElementById(objid);

}

// open new window
var myWindow;
function show(url,wi,he,title_win,full) {
	
	if (myWindow != null){
		myWindow.close();
		myWindow = null;
	}
	var lpos = (screen.width) ? (screen.width-wi)/2 : 0;
	var tpos = (screen.height) ? (screen.height-he)/2 : 0;
	myWindow = window.open(url, title_win, "top="+tpos+",left="+lpos+",toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,personalbar=no,resizable=no,width=" + wi + ",height=" + he + ",outerheight=0,outerwidth=0");
                
	myWindow.focus();
                
} 
        
function show_resized(url,wi,he,title_win) {
	
	if (myWindow != null){
		myWindow.close();
		myWindow = null;
	}
	
	// check for auto resizing
	if (wi == 'auto')
		wi = screen.width;//getClientWidth(true);
	if (he == 'auto')
		he = screen.height;//getClientHeight(true);
	var lpos = (screen.width) ? (screen.width-wi)/2 : 0;
	var tpos = (screen.height) ? (screen.height-he)/2 : 0;
	myWindow = window.open(url, title_win, "top="+tpos+",left="+lpos+",toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,personalbar=no,resizable=yes,width=" + wi + ",height=" + he + ",outerheight=0,outerwidth=0");
	
}

function show_resized_scroll(url,wi,he,title_win) {
	
	if (myWindow != null){
		myWindow.close();
		myWindow = null;
	}
	
	var lpos = (screen.width) ? (screen.width-wi)/2 : 0;
	var tpos = (screen.height) ? (screen.height-he)/2 : 0;
	myWindow = window.open(url, title_win, "top="+tpos+",left="+lpos+",toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,personalbar=no,resizable=yes,width=" + wi + ",height=" + he + ",outerheight=0,outerwidth=0");
	
}




function sethome(o,siteurl,sitename) {
	var name = navigator.appName;
	var useragent = navigator.userAgent;
	var version = parseInt(navigator.appVersion);
	var needtoknow = 1;
	
	if ( useragent.indexOf("MSIE") != -1) {
			var index = navigator.userAgent.indexOf("MSIE ");
			if ( index != -1 ) {
				version = parseInt(navigator.userAgent.substring(index+5,index+6));
			}
			if ( version > 4) {
				o.style.behavior='url(#default#homepage)'; o.setHomePage(siteurl);
				needtoknow = 0;
			}
	}
//	if (needtoknow != 0) {
	//	alert('/help/makehomepage.html','winMakeHomepage','location=no,menubar=no,scrollbars=yes,resizable=yes,width=500,height=450');
	//}
}

function right_escape(s){
	// BE Careful - encodeURI works badly!!!
	//if(self.encodeURI)  return encodeURI(s); //standart method
	//if we have not found 
	var res="";
	for(var i=0, cnt=s.length ;i<cnt;i++){
		//try to recode
		/*if (utf8_rus[s.charAt(i)] != null) res+=utf8_rus[s.charAt(i)];
		else */res+=s.charAt(i);
	}
	return res;
}

function getClientWidth(is_top){
	var bOpera = false,ver = navigator.appVersion.match("^[0-9\.]+");
	if (window.opera && parseFloat(ver) < 9)
		bOpera = true;

	if (typeof is_top != 'undefined' && is_top){
		var curr_frame = top.document;
	} else
		var curr_frame = document;
	return document.compatMode=='CSS1Compat' && !window.opera ? curr_frame.documentElement.clientWidth : curr_frame.body.clientWidth;
}

function getClientHeight(is_top){
	var bOpera = false,ver = navigator.appVersion.match("^[0-9\.]+");
	if (window.opera && parseFloat(ver) < 9)
		bOpera = true;
		
	if (typeof is_top != 'undefined' && is_top){
		var curr_frame = top.document;
	} else
		var curr_frame = document;
	
	return document.compatMode=='CSS1Compat' && !bOpera ? curr_frame.documentElement.clientHeight : curr_frame.body.clientHeight;
}



/* json function */
function addToJson(json, elemname, value){
	json[elemname] = value;
}

function removeFromJson(json, elemname){
	delete json[elemname];
}

function getStyle(el,styleProp)
{
	var x = typeof el == 'string' ? document.getElementById(el) : el;
	if (x){
		if (typeof x.currentStyle != 'undefined' && typeof x.currentStyle != 'null'){
			// update calling value - remove '-' and move to upervase first symbol
			styleProp = styleProp.replace(/\-([^-])?/, function(s){return s.toUpperCase()}).replace(/\-/, '');
			var y = x.currentStyle[styleProp];
		} else if (window.getComputedStyle)
			var y = document.defaultView.getComputedStyle(x,null).getPropertyValue(styleProp);
	}
	return y;
}

function getLikeElements(tagName, attrName, attrValue) {
    var startSet;
    var endSet = new Array();
    if (tagName) {
        startSet = document.getElementsByTagName(tagName);    
    } else {
        startSet = (document.all && !window.opera) ? document.all : 
            document.getElementsByTagName("*");
    }
   // alert(attrName)
    if (attrName) {
        for (var i = 0; i < startSet.length; i++) {
            if (startSet[i] && startSet[i].getAttribute(attrName)) {
                if (attrValue) {
                    if (startSet[i] && startSet[i].getAttribute(attrName) == attrValue) {
                        endSet[endSet.length] = startSet[i];
                    }
                } else {
                    endSet[endSet.length] = startSet[i];
                }
            }
        }
    } else {
        endSet = startSet;
    }
    return endSet;
 
}


// date functions
function timeSource(){
	var x=new Date(timeNow().getUTCFullYear(),timeNow().getUTCMonth(),timeNow().getUTCDate(),timeNow().getUTCHours(),timeNow().getUTCMinutes(),timeNow().getUTCSeconds());
	x.setTime(x.getTime()+10800000);
	return x;
}
function timeNow(){
	return new Date();
}
function leadingZero(x){
	return (x>9)?x:'0'+x;
}
function displayTime(){
   $_('disp').innerHTML=eval(outputTime);
   setTimeout('displayTime()',1000);
}
var outputTime="leadingZero(timeSource().getHours())+':'+leadingZero(timeSource().getMinutes())+':'+leadingZero(timeSource().getSeconds())";

function strt(){
	displayTime();
}


function bookmark(){
    var title= document.title;
    var url= location.href;

    if (window.sidebar) 
    	window.sidebar.addPanel(title, url,"");
    else if( window.opera && window.print )
    {
    var mbm = document.createElement('a');
    mbm.setAttribute('rel','sidebar');
    mbm.setAttribute('href',url);
    mbm.setAttribute('title',title);
    mbm.click();
    }
    else if( document.all ) window.external.AddFavorite( url, title);
} 


// pager key-code checker 
var CheckKeyCodePgr = function(event, uid){
	if ({13:1}[event.which||event.keyCode]){
		return eval("pager_on_chg"+uid);
	}
			
	keycode = event.which ? event.which : event.keyCode;

	if((keycode >= 48 && keycode <= 57) || (keycode >= 37 && keycode <= 40) || keycode == 8) {
		return true; 
	} else {
		return false;
	}
};


// Ajax pager key-code checker 
var CheckKeyCodePgrAjx = function(event, uid){
	if ({13:1}[event.which||event.keyCode]){
		updPage($_("newppage"+uid).value);
		return false;
	}
			
	keycode = event.which ? event.which : event.keyCode;

	if((keycode >= 48 && keycode <= 57) || (keycode >= 37 && keycode <= 40) || keycode == 8) {
		return true; 
	} else {
		return false;
	}
};


/* check for event keyCode and execute function  if it is Enter */
function sbmtKeyChecker(event, func){

	if ({13:1}[event.which||event.keyCode]){
		eval(func);
		return false;
	}
	
}


/**
* function show/hide element
* @version 1.4
*
* Changelog:
*	1.4	10.03.10/goshi	oId now can be an object
*	1.3	14.10.09/goshi	add callback
*	1.2	16.07.09/goshi	add closeOnOutClick
*	1.1	09.11.08/goshi	added returned value
* 	1.0	20.08.08	
*/
function showHide(oId, closeOnOutClick, callback){
	if (typeof oId != 'object')
		var aObj = $_(oId);
	else
		var aObj = oId;
	
	if (aObj){
		if (aObj.style.display == 'none'){
			aObj.style.display = '';
			if (typeof closeOnOutClick != "undefined" && closeOnOutClick){
				setTimeout("portal.events.attach(document, 'mouseup', function (evt){showHide('"+aObj.id+"', "+closeOnOutClick+")});", 200);
			}			
		}else{
			aObj.style.display = 'none';
			if (typeof closeOnOutClick != "undefined" && closeOnOutClick){
				portal.events.remove(document, 'mouseup');
			}
		}
		
		if ((typeof callback).toLowerCase() == "function"){
			callback();
		}
		// fix Opera bug
		if (window.opera)
			document.body.style += '';
		
		return aObj.style.display;
	}
}

function Hide(oId){
	var aObj = $_(oId);
	aObj.style.display = 'none';
}


/* working with tabs */
function sw_tab (aobj, holder) {
	
	var j=0;
	var obj = $_(aobj);
	while ($_(holder+"_"+ j)&& $_(holder+"_"+ j)!="undefined"){
		if ($_(holder+"_"+ j)!=obj)
		{
		$_(holder+"_"+ j).className = '';
		$_(holder+"_h_"+ j).style.display = 'none';
		}
		else 
		{
			$_(holder+"_h_"+ j).style.display = 'block';
			}
		j++;
	}
	
	if (obj){
		obj.className = 'act';
		obj.blur();
	}
	return false;
};



/*
*	TAB switcher
*	0.3	21.02.10/goshi	move imgTabs to function
*	0.2	16.11.08/goshi	remove bug with switcher, when it is undefined
*/
function switchTab(aobj, holder){
	var j=0;
	var obj = $_(aobj);
	
	var imgTabs = new Array();
	imgTabs[0] = new Image();
	imgTabs[0].src = skin_img_dir + 'l_options_agreed.gif'; // for show
	imgTabs[1] = new Image();
	imgTabs[1].src = skin_img_dir + 'l_options_agreed_off.gif'; // for hide
	
	if (typeof obj != "undefined" && obj){
		while (typeof $_(holder+"_"+ j) != "undefined" && $_(holder+"_"+ j)){
			
			if ($_(holder+"_"+ j) == obj){
				// saving in user session and switch data
				var tmp_state = showHide(holder+"_"+"h_"+j);
				var switchers = portal.session.get('switchers');
				if (typeof switchers == "undefined")
					var switchers = new Object;
				
				switchers[aobj] = {
					'func': 'switchTab',
					'params': [aobj, holder],
					'initstate': 'none',
					'currstate': tmp_state
					};
				
				portal.session.set('switchers', switchers);
				var switchers = portal.session.get('switchers');
				
				if (tmp_state == 'none'){
					obj.src = imgTabs[1].src;					
				} else {
					obj.src = imgTabs[0].src;
				}
				
				return false;
			}
			j++;
		}
			
		
		obj.blur();
	}
	return false;
}


/*
* Unswitcher function
* make state for portal.session.switchers variable
* You can call this function only after DOM is ready (in onload event)
*
* ver 0.1
*
* History:
*	0.1	10.11.08/goshi	
*/
function unSwitcher(){

	var tmp = portal.session.get('switchers');
	
	if (tmp != undefined){
		
		for (var i in tmp){	
			// check for function enabled and init state - in some cases init state may be equivalent to the saved state
			// then - don nothing
			if (eval('window.'+tmp[i].func) && tmp[i].initstate != tmp[i].currstate){
				//alert(tmp[i].func+"("+unescape(tmp[i].params.join())+")");
				var params = '';
				for (var j in tmp[i].params){
					params += "'"+tmp[i].params[j]+"',";
				}
				if (params != ''){
					params = params.substring(0, params.length-1);
				}
				eval(tmp[i].func+"("+params+")");
			}
										
		}
	}

}

// trim functions
function trim(str, chars) {
	return ltrim(rtrim(str, chars), chars);
}
 
function ltrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}
 
function rtrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}
