/*
* BCLub JS Library fpr PowerPHP
* ver 1.0
*
* History:
* 	1.0	12.09.08	
*/


function do_nothing(){

return void(0);

}

function $_(objid){

	return document.getElementById(objid);

}

// open new window
var myWindow;
function show(url,wi,he,title_win) {
	
	if (myWindow != null){
		myWindow.close();
		myWindow = null;
	}
	lpos = (screen.width) ? (screen.width-wi)/2 : 0;
	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) {
	
	lpos = (screen.width) ? (screen.width-wi)/2 : 0;
	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;
	}
	
	lpos = (screen.width) ? (screen.width-wi)/2 : 0;
	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");
	
}
/*var myWindow;
function show(url,wi,he,title_win) {
	
	myWindow = window.open(url, title_win, "toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,personalbar=no,resizable=no,width=" + wi + ",height=" + he + ",outerheight=0,outerwidth=0");
}  

function show_resized(url,wi,he,title_win) {
	
	myWindow = window.open(url, title_win, "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 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 
	res="";
	for(i=0;i<s.length;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()
{
  return document.compatMode=='CSS1Compat' && !window.opera?document.documentElement.clientWidth:document.body.clientWidth;
}

function getClientHeight()
{
 return document.compatMode=='CSS1Compat' && !window.opera?document.documentElement.clientHeight:document.body.clientHeight;
}

/**
 	* This array is used to remember mark status of rows in browse mode
 	*/
	var marked_row = new Array; 
 
        /**
 	* Sets/unsets the pointer and marker in browse mode
 	*
 	* @param   object    the table row
 	* @param   integer  the row number
 	* @param   string    the action calling this script (over, out or click)
 	* @param   string    the default background color
 	* @param   string    the color to use for mouseover
 	* @param   string    the color to use for marking a row
 	*
 	* @return  boolean  whether pointer is set or not
 	*/
	function setPointer(theRow, theRowNum, theAction, theDefaultColor, thePointerColor, theMarkColor)
	{
   	 var theCells = null;

   	 // 1. Pointer and mark feature are disabled or the browser can't get the
    	//    row -> exits
    	if ((thePointerColor == '' && theMarkColor == '')
      	  || typeof(theRow.style) == undefined) {
     	   return false;
    	}

    	// 2. Gets the current row and exits if the browser can't get it
    	if (typeof(document.getElementsByTagName) != undefined) {
     	   theCells = theRow.getElementsByTagName('td');
    	}
    	else if (typeof(theRow.cells) != undefined) {
        	theCells = theRow.cells;
    	}
    	else {
        	return false;
    	}

    	// 3. Gets the current color...
    	var rowCellsCnt  = theCells.length;
    	var domDetect    = null;
    	var currentColor = null;
    	var newColor     = null;
    	// 3.1 ... with DOM compatible browsers except Opera that does not return
    	//         valid values with "getAttribute"
    	if (typeof(window.opera) == undefined
        	&& typeof(theCells[0].getAttribute) != undefined) {
        	currentColor = theCells[0].getAttribute('bgcolor');
        	domDetect    = true;
    	}
    	// 3.2 ... with other browsers
    	else {
        	currentColor = theCells[0].style.backgroundColor;
        	domDetect    = false;
    	} // end 3

    	// 3.3 ... Opera changes colors set via HTML to rgb(r,g,b) format so fix it
    	if (currentColor.indexOf("rgb") >= 0)
    	{
        	var rgbStr = currentColor.slice(currentColor.indexOf('(') + 1,
                                     currentColor.indexOf(')'));
        	var rgbValues = rgbStr.split(",");
        	currentColor = "#";
        	var hexChars = "0123456789ABCDEF";
        	for (var i = 0; i < 3; i++)
        	{
            	var v = rgbValues[i].valueOf();
            	currentColor += hexChars.charAt(v/16) + hexChars.charAt(v%16);
        	}
    	}

    	// 4. Defines the new color
    	// 4.1 Current color is the default one
    	if (currentColor == ''
        	|| currentColor.toLowerCase() == theDefaultColor.toLowerCase()) {
        	if (theAction == 'over' && thePointerColor != '') {
            		newColor = thePointerColor;
        	}
        	else if (theAction == 'click' && theMarkColor != '') {
            		newColor              = theMarkColor;
            		marked_row[theRowNum] = true;
            	// Garvin: deactivated onclick marking of the checkbox because it's also executed
            	// when an action (like edit/delete) on a single item is performed. Then the checkbox
            	// would get deactived, even though we need it activated. Maybe there is a way
            	// to detect if the row was clicked, and not an item therein...
            	// $_('id_rows_to_delete' + theRowNum).checked = true;
        	}
    	}
    	// 4.1.2 Current color is the pointer one
    	else if (currentColor.toLowerCase() == thePointerColor.toLowerCase()
             	&& (typeof(marked_row[theRowNum]) == undefined || !marked_row[theRowNum])) {
        	if (theAction == 'out') {
            		newColor              = theDefaultColor;
        	}
        	else if (theAction == 'click' && theMarkColor != '') {
            		newColor              = theMarkColor;
            		marked_row[theRowNum] = true;
            		// $_('id_rows_to_delete' + theRowNum).checked = true;
        	}
    	}
    	// 4.1.3 Current color is the marker one
    	else if (currentColor.toLowerCase() == theMarkColor.toLowerCase()) {
        	if (theAction == 'click') {
            	newColor              = (thePointerColor != '')
              	                   	? thePointerColor
              	                   	: theDefaultColor;
            	marked_row[theRowNum] = (typeof(marked_row[theRowNum]) == undefined || !marked_row[theRowNum])
                                  	? true
                                  	: null;
            	// $_('id_rows_to_delete' + theRowNum).checked = false;
        	}
    	} // end 4

    	// 5. Sets the new color...
    	if (newColor) {
        	var c = null;
        	// 5.1 ... with DOM compatible browsers except Opera
        	if (domDetect) {
            	for (c = 0; c < rowCellsCnt; c++) {
                	theCells[c].setAttribute('bgcolor', newColor, 0);
            	} // end for
        	}
        	// 5.2 ... with other browsers
        	else {
            		for (c = 0; c < rowCellsCnt; c++) {
                		theCells[c].style.backgroundColor = newColor;
            		}
        	}
    	} // end 5

    	return true;
	} // end of the 'setPointer()' function 
	

// function working with cookies
function setCookie (name, value, expires, path, domain, secure) {
      document.cookie = name + "=" + escape(value) +
        ((expires) ? "; expires=" + expires : "") +
        ((path) ? "; path=" + path : "") +
        ((domain) ? "; domain=" + domain : "") +
        ((secure) ? "; secure" : "");
}

function getCookie(name) {
	var cookie = " " + document.cookie;
	var search = " " + name + "=";
	var setStr = null;
	var offset = 0;
	var end = 0;
	if (cookie.length > 0) {
		offset = cookie.indexOf(search);
		if (offset != -1) {
			offset += search.length;
			end = cookie.indexOf(";", offset);
			if (end == -1) {
				end = cookie.length;
			}
			setStr = unescape(cookie.substring(offset, end));
		}
	}
	return(setStr);
}

/* 
* function for working with arrays and objects
* ver 2.0
*
* History:
*	2.0	10.11.2008/goshi	using O'Reilies library
*
* @isArray bool set ti true, if value is array, default - false
*/
function setCookieArr (name, value, expires, path, domain, secure, isArray) {

	if (isArray != undefined && isArray == true){
		setCookie(name, array2String(value), expires, path, domain, secure);
	} else {
		setCookie(name, object2String(value), expires, path, domain, secure);
	}
	          
}


/*
* ver 2.0
*
* History:
*	2.0	10.11.08	using for converting o'Reillies library
*	1.1	29.08.08	added check for tmp var
*/
function getCookieArr (name, isArray) {

	var tmp = getCookie(name);
	if (tmp && tmp.length > 0){
		if (isArray != undefined && isArray == true){
			return string2Array(tmp);
		} else {
			return string2Object(tmp);
		}
	} else {
		return false;
	}

    /* var tmp = getCookie(name);
     var json = {};
     if (tmp && tmp.length > 0) {
     	var tmpb = tmp.split(',');
     	for (var i=0;i<tmpb.length;i++){
     		//alert("tmpb["+i+"]='"+tmpb[i]+"'");
     		if (tmpb[i] != '' || tmpb[i] != 0) json[tmpb[i]] = 1;
     	}
     }
     return json; */
}



/* json function */
function addToJson(json, elemname, value){
	json[elemname] = value;
}

function removeFromJson(json, elemname){
	delete json[elemname];
}

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;
 
}


/* 
* Session cookie prototype 
* ver 0.2
*
* History:
*	0.2	10.11.08/goshi	remove bug with initial setting for session cookie
*	0.1	10.11.08/goshi
*/
function pphpSession(){
	this._init();
}

pphpSession.prototype = {

	// because session data is dynamic - we must not set _values for long time - only for temporary cache for updating
	_values: new Object(),
	
	_init: function(){
		this._values = getCookieArr(session_name);
		
		if (this._values == undefined || this._values == false){
			
			this._values = new Object();
			var expires = new Date();
			expires.setTime(expires.getTime() + max_cookie_life);
			
			setCookieArr(session_name, this._values, expires, "/");
					
		}
		
		// setting up switchers
		
		if (this._values['switchers'] == undefined){
		
			this._values['switchers'] = new Object();
			this.setValue('switchers', this._values['switchers']);
			
		}
	},
	
	getValue: function(valueName){
		this._values = getCookieArr(session_name);
		if (this._values[valueName] != undefined && this._values[valueName] != ''){
			return this._values[valueName];
		}
	},
	
	setValue: function(valueName, value){
		this._values = getCookieArr(session_name);
		this._values[valueName] = value;
		var expires = new Date();
		expires.setTime(expires.getTime() + max_cookie_life);
		setCookieArr(session_name, this._values, expires, "/");
	}

};

var uSession = new pphpSession();


// date functions
function timeSource(){
   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 
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 
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;
	}
};


/* DOM function for creating or removing elements */
function elem(name, attrs, style, text) {
    var e = document.createElement(name);
    if (attrs) {
        for (key in attrs) {
            if (key == 'class') {
                e.className = attrs[key];
            } else if (key == 'id') {
                e.id = attrs[key];
            } else {
                e.setAttribute(key, attrs[key]);
            }
        }
    }
    if (style) {
        for (key in style) {
            e.style[key] = style[key];
        }
    }
    if (text) {
        e.appendChild(document.createTextNode(text));
    }
    return e;
}

/*
* function show/hide eleemnt
* ver 1.1
*
* History:
*	1.1	09.11.08/goshi	added returned value
* 	1.0	20.08.08	
*/
function showHide(oId){
	var aObj = $_(oId);
	if (aObj){
		if (aObj.style.display == 'none'){
			aObj.style.display = 'block';
		}else{
			aObj.style.display = 'none';
		}
		
		return aObj.style.display;
	}
}

/* specified function for bclub */
function langDrop() {
	if ($_('langDrop').className == '') {
		$_('langDrop').className = 'show';
	} else {
		$_('langDrop').className = ''; 
	}
}

/* visual image for loading */
var imgLoader = new Image();
imgLoader.src = skin_img_dir + "loader.gif";

function showLoader(objid){

	var obj = $_(objid);
	// generate uniq id - we need to initialize date object each time for unique id
	var tmpdt = new Date;
	var id = tmpdt.getTime();
		
	if (obj){
		obj.innerHTML = '<span class="loader" id="loader_'+id+'"><img id="iloader_'+id+'" src="'+imgLoader.src+'" /></span>';
		
	}
}


/* 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 = 'small-bm';
		$_(holder+"_h_"+ j).style.display = 'none';
		}
		else 
		{
			$_(holder+"_h_"+ j).style.display = 'block';
			}
		j++;
		}
	obj.className = 'small-bm-act';
	obj.blur();
	return false;
};

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

function img_tab (aobj, holder) {
	
	var j=0;
	var obj = $_(aobj);
	while ($_(holder+"_"+ j) && $_(holder+"_"+ j)!="undefined"){
		if ($_(holder+"_"+ j)!=obj)
		{
			$_(holder+"_"+ j).className = 'small-bm';
			$_(holder+"_h_"+ j).style.display = 'none';
		} else {
			$_(holder+"_h_"+ j).style.display = 'block';
		}
		j++;
	}
	obj.src = imgTabs[0].src;
	obj.blur();
	return false;
};

/*
*	TAB switcher
*	0.2	16.11.08/goshi	remove bug with switcher, when it is undefined
*/
function switchTab(aobj, holder){
	var j=0;
	var obj = $_(aobj);
	if (obj != undefined){
		while ($_(holder+"_"+ j) && $_(holder+"_"+ j)!="undefined"){
			if ($_(holder+"_"+ j) == obj){
				// saving in user session and switch data
				var tmp_state = showHide(holder+"_"+"h_"+j);
				var switchers = uSession.getValue('switchers');
				
				switchers[aobj] = {
					'func': 'switchTab',
					'params': [aobj, holder],
					'initstate': 'none',
					'currstate': tmp_state
					};
				
							
				uSession.setValue('switchers', switchers);
				
				var switchers = uSession.getValue('switchers');
				
				if (tmp_state == 'block'){
					obj.src = imgTabs[0].src;
				} else {
					obj.src = imgTabs[1].src;
				}
	
				
				return false;
			}
			j++;
		}
		
		obj.blur();
	}
	return false;
}


/*
* Unswitcher function
* make state for uSession.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 = uSession.getValue('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+")");
			}
										
		}
	}

}



/* 
array functions 
30.11.08/goshi
*/
function in_array(needle, haystack) {
	
	for (var i = 0, loopCnt = haystack.length; i < loopCnt; i++) {
		alert(this.i + "=" + needle);
		if (this.i === needle) {
			return true;
		}
	}
		
	return false;
};

