/**
*	Common Javascript library for web-T::CMS
*	Must go first in connection map 
*	@author	goshi
*	@version 1.9
*	@package javascript::share
*
*	Changelog:
*	1.9		12.06.10/goshi	move all obj2str and cookies functions to the common.js
*	1.8		06.03.10/goshi	add share and project dirs
*	1.71	22.10.09/goshi	fix url in reg_str
*	1.7		10.07.09/goshi	add url to regular_str
*	1.6		02.04.09/goshi	add addLoadEvent for multiple onload events
*	1.5		10.02.09/goshi	add oStorage and instance in portal.storage, oPortal into separate files, add elem function, domReady function
*	1.1		24.01.09/goshi	remove bug for opera and portal object exists
*	1.0		17.01.09/goshi	add portal object
*/


// skin images
var skin_img_dir = '/skin/img/';
var project_dir = 'project/';
var share_dir = 'share/';

//var lang_dir = '/languages/';

// user session name
var session_name = 'pphp_session';

// max cookie life - half of the year
var max_cookie_life = 60*60*24*180;

/* regular expressions for form elements */
var regulars = { 
	'email' : /[0-9a-z_\.-]+@[0-9a-z_^\.-]+.[a-z]{2,6}/i,
	'url' : /(http):\/\/([_a-z\d\-]+(\.[_a-z\d\-]+)+)(([_a-z\d\-\\\.\/])+[_a-z\d\-\\\/])/i,
	'date_time' : /\d{4}-\d{2}-\d{2}\s(\d{1,2}):(\d{1,2}):(\d{1,2})/i,
	'date' : /\d{4}-\d{1,2}-\d{1,2}/i
}

var regular_str = {
	'normal_datetime' : '^[0-9]{2}:[0-9]{2}(?::[0-9]{2})? [0-9]{2}\\-[0-9]{2}\\-[0-9]{4}$',
	'time' : '^([0-1][0-9]|2[0-3]):[0-5][0-9]$',
	'email' : '^[0-9a-z_\\.-]+@[0-9a-z_^\\.-]+.[a-z]{2,6}$',
	'url' : '^((http):\\/\\/([_a-z\\d\\-]+(\\.[_a-z\\d\\-]+)+)(([_a-z\\d\\-\\\\\.\\/])+[_a-z\\d\\-\\\\\/]))*$',
	'nick' : '^[0-9a-zA-Z_\-]*$'
}


/**
* DOM function for creating or removing elements 
* @version 2.0
*
* Changelog:
*	2.0	20.04.09/goshi	support multilanguage system
*
*/
function elem(name, attrs, style, text, is_multilang) {

	if (typeof is_multilang != "undefined" && is_multilang){
	
		var e = document.createDocumentFragment();
		var new_attrs = attrs;
		// copy object - from reference
		if (new_attrs){
			var old_values = new_attrs['value'];
			var old_name = new_attrs['name'];
		}
		var new_style = style ? style : {};

		for (var i in portal.vars.langs){
			
			new_attrs['lang'] = i;
			new_attrs['name'] = old_name+'['+i+']';
			if (attrs['value'])
				new_attrs['value'] = old_values[i];
			
			new_style['display'] = (typeof LangController != "undefined" && LangController._curr_lang == i ? '' : 'none');
			new_style['backgroundImage'] = 'url('+portal.vars.langs[i]['img']+')';
			new_style['backgroundPosition'] = 'left center';
			new_style['backgroundRepeat'] = 'no-repeat';
			new_style['paddingLeft'] = '20px';
			
			e.appendChild(elem(name,
				new_attrs,
				new_style,
				text
				));
			
		}
		
		return e;
			
	} else {

	    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 add onload event listener - it is optimize for multiple nload events on page 
*/
function addLoadEvent(func) {
	var oldonload = window.onload;
	if (typeof window.onload != 'function') {
		window.onload = func;
	} else {
		window.onload = function() {
			if (oldonload) { oldonload(); }
			func();
		}
	}
}


/**
* DOM Ready function - if you want to wait until all elemsnts on the page were loaded
* Copyright http://ajaxian.com/ 
*/
function domReady(i) { 		

	var u =navigator.userAgent;
	var e=/*@cc_on!@*/false;
	var st = setTimeout;
	if (/webkit/i.test(u)) {
		st(
			function() {
				var dr=document.readyState;
				if(dr=="loaded"||dr=="complete") i();
				else st(arguments.callee,10);
			},
			10
		);
	} else if ((/mozilla/i.test(u)&&!/(compati)/.test(u)) || (/opera/i.test(u))) {
		document.addEventListener("DOMContentLoaded", i, false);
	} else if (e) {(
		function(){
			var t=document.createElement('doc:rdy');
			
			try {
				t.doScroll('left'); i(); t=null;
			} catch(e) {st(arguments.callee,10);}
		})();
	} else addLoadEvent(i);
	
}

/**
* function syncing events 
*
* param {function} k	function, that execute after right condition
* param {String} condition	while not condition true  - function not execute
*/
function syncEvent(k, condition){

	(function(){	
		try{
			//portal.debug.dump('cond:'+eval(condition), true);	
			if (eval(condition) == true) {
				k();
			} else {
				setTimeout(arguments.callee,10);
			}
		} catch(e) {
			//portal.debug.dump('error:'+e, true);	
			
			setTimeout(arguments.callee,10);
		}}
	)();
}

/**
* O'Reillies library for converting objects and arrays to strings
* @version 1.1
*
* Changelog:
*	1.1 11.11.08/goshi	remove bug with conveting empty object to string
*/
function object2String(obj) {
    var val, count = 0, output = "";
    if (obj) {    
        output += "{";
        
        for (var i in obj) {
            val = obj[i];
            switch (typeof val) {
                case ("object"):
                    if (val[0]) {
                        output += i + ":" + array2String(val) + ",";
                    } else {
                        output += i + ":" + object2String(val) + ",";
                    }
                    break;
                case ("string"):
                    output += i + ":'" + escape(val) + "',";
                    break;
                default:
                    output += i + ":" + val + ",";
            }
            
            count++;
        }
        // removed bug with empty object
        if (count == 0)
        	output = output + "}";
        else
        	output = output.substring(0, output.length-1) + "}";
    }
    return output;
}
   
function array2String(array) {
    var output = "";
    if (array) {
        output += "[";
        for (var i in array) {
            val = array[i];
            switch (typeof val) {
                case ("object"):
                    if (val[0]) {
                        output += array2String(val) + ",";
                    } else {
                        output += object2String(val) + ",";
                    }
                    break;
                case ("string"):
                    output += "'" + escape(val) + "',";
                    break;
                default:
                    output += val + ",";
            }
        }
          // removed bug with empty object
        if (array.length == 0)
        	output = output + "]";
        else
        	output = output.substring(0, output.length-1) + "]";
        
    }
    return output;
}
   
function string2Object(string) {
    eval("var result = " + string);
    return result;
}
   
function string2Array(string) {
    eval("var result = " + string);
    return result;
}


/**
* cookies library
*
* @author goshi
* @package javascript::share
*/
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
* @version 2.0
*
* Changelog:
*	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);
	}
	          
}


/**
* @version 2.0
*
* Changelog:
*	2.0	10.11.08/goshi	using for converting o'Reillies library
*	1.1	29.08.08/goshi	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; */
}