function ById(id)
{
    return (typeof id == "object" && id !== null) ? id : document.getElementById(id);
}

String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g,"");
}

String.prototype.br2nl = function() {
	return this.replace(/<br.*?>/gi,"\r\n");
}

String.prototype.strip_tags = function() {
    return this.replace(/<.*?>/ig,"");
}

String.prototype.deleteMultipleNL = function() {
	return this.replace(/(\s){2,}/g,"\r\n");
}

function PopupChat(receiver_id,chatsession_id)
{
    var path = '/chat/,' + receiver_id + '';
    if (chatsession_id) {
        path += ',' + chatsession_id + '';
    }
    window.open(path, 'chatWindow_'+receiver_id+'', 'width=800,height=400,resizable=yes');
}

function PopupGroupChat(group_id,chatsession_id)
{
    var path = '/groupchat/,' + group_id + '';
    if (chatsession_id) {
        path += ',' + chatsession_id + '';
    }
    window.open(path, 'chatWindow_'+group_id+'', 'width=800,height=400,resizable=yes');
}

function PopupTopicPreview()
{
    window.open('/board/preview_topic/', 'preview_topic', 'width=1000,height=400,resizable=yes,scrollbars=yes');
}

function PopupPostPreview()
{
    window.open('/board/preview_post/', 'preview_post', 'width=1000,height=400,resizable=yes,scrollbars=yes');
}

function isNumeric(sText)
{
    var ValidChars = "-0123456789.,";
    var IsNumber=true;
    var Char;
    for (var i = 0; i < sText.length && IsNumber == true; i++) {
        Char = sText.charAt(i);
        if (ValidChars.indexOf(Char) == -1) {
            IsNumber = false;
        }
    }
    return IsNumber;
}

function postCodeCompletion(obj) {
	for (var x = 0; x < obj.value.length; x++) {

		if (isNaN(obj.value.charAt(x)) && (x != 2 && obj.value.charAt(x) != '-')) {
			before = obj.value.substr(0, x);
			after = obj.value.substr(x+1, 20);
			obj.value = before + after;
			postCodeCompletion(obj);
		}

	}

	if (obj.value.length > 2 && obj.value.charAt(2) != '-') {
		after = obj.value.substr(2, 6);
		obj.value = "" + obj.value.substr(0, 2) + '-';
		obj.value = obj.value + after;
	}

	if (obj.value.length > 6) {
		obj.value = obj.value.substr(0, 6);
	}

}

function showHide(warstwa)
{
	if (ById(warstwa).style.display == 'none') visibleornot = 'block';
	else visibleornot = 'none'
	ById(warstwa).style.display = visibleornot;
}

var show_objects = new Array();

function show(obj, display)
{
	if( ById(obj) ) obj = ById(obj);

	if( !display || display == undefined ) display = 'block';

	if( obj ) {

		if( show_objects[obj.id] != undefined && show_objects[obj.id] != '' ) {

			obj.style.display = show_objects[obj.id];
			show_objects[obj.id] = '';

		} else {

			show_objects[obj.id] = obj.style.display;
			obj.style.display = display;

		}

	}

}

function hide(obj)
{
    ById(obj).style.display = 'none';
};

/* Funkcja do pobierania miast na podstawie kodu pocztowego */
postCodeCache = new Array();
function CheckPostCodeJS(postcode_field_id, city_field_id, postcode_id_field_id, region_field_id) {

	postcode 	= ById(postcode_field_id).value;
	city		= ById(city_field_id).value;

	if( postCodeCache['city'] && postCodeCache['city'] == city ) {
		city = ' ';
	}

	advAJAX.post({

		url: '/register/ajax/postcodecheck/',

		uniqueParameter: "custom_unique_param",

		parameters : {
			"postcodecheck[postcode]"	:	postcode,
			"postcodecheck[city]"		:	city
		},

	    onInitialization : function() {
		},

	    onSuccess : function(obj) {
	    },

	    onError : function(obj) {
	        alert("Error: " + obj.status);
	    },

	    onFinalization : function(obj) {

	    	pc = obj.responseText;

	    	if( pc=='' ) {
	    		return false;
	    	}

	    	data = pc.split(';');

	    	if( !data[0] || data[0] == 'false' || data[0] == '0' || data[0] == '' ) {

				if( data[0] == '0' ) {
					alert('Proszę sprawdzić wpisany kod pocztowy.\nJeśli jest on wpisany poprawnie prosimy jeszcze uzupełnić miejscowość i wojewótdzwo.');
					data[2] = '';
				} else {
					alert('Proszę sprawdzić wpisany kod pocztowy.');
				}
			} else {
			}
			postCodeCache['postcode_id'] = ById(postcode_id_field_id).value 	= data[0];
			postCodeCache['postcode']															= data[1];
	    	postCodeCache['city'] 		 = ById(city_field_id).value 		= data[2];


	    	arrSelect = ById(region_field_id);

			for (i = 0; i < arrSelect.length; i++) {

				if(arrSelect.options[i].text == data[3]) {
					ById(region_field_id).options.selectedIndex = i;
					break;
				} else {
					ById(region_field_id).options.selectedIndex = 0;
				}

			}

			if( data[0] == 0 ) {
	    		return false;
	    	}

	    }

	});

	check = ById(postcode_id_field_id).value;

	if( !check || check == 'false' || check == '0' || check == '' ) {
		return false;
	}

}

function tillNow(obj, id_part, prefix){

	if( prefix ) prefix += "_";
	else prefix = "";

	if(obj.checked) {
		show(prefix+"date_to_"+id_part+"_month",'none');
		show(prefix+"date_to_"+id_part+"_year",'none');
	} else {
		show(prefix+"date_to_"+id_part+"_month",'inline');
		show(prefix+"date_to_"+id_part+"_year",'inline');
	}

}

var erased = new Array();
function eraseOnce(obj){
	if(erased[obj.id]!=true) {
		obj.value="";
		erased[obj.id]=true;
	}
}

function eraseIf(obj, condition){
	if(obj.value==condition) {
		obj.value = '';
	}
}

function reWrite(id1, id2) {

	obj1 = ById(id1);
	obj2 = ById(id2);

	if( obj1.value != undefined ) {

		text1 = obj1.value;

	} else if (obj1.innerHTML != undefined) {

		text1 = obj1.innerHTML;

	}

	if( obj2.value != undefined ) {

		obj2.value = text1;

	} else if (obj2.innerHTML != undefined) {

		obj2.innerHTML = text1;

	}

}

function Loading(obj)
{
	if( typeof(obj) == 'string' ) obj = ById(obj);
	obj.innerHTML = '<img src="/_p/img/ajax-loader.gif" alt="Ładowanie" />';
	return true;
}

var wizardSwitch;
function wizardSetting(obj)
{
	if (obj.checked == true) {
		var on_off = 't';
	} else {
		var on_off = 'f';
	}
	advAJAX.post({
		url: '/content/wizard/',
		uniqueParameter: "custom_unique_param",
		parameters : {
			"wizard_settings[on_off]"		:	on_off
		},
	    onInitialization : function() {
		},
	    onSuccess : function(obj) {
	    },
	    onError : function(obj) {
	        alert("Error: " + obj.status);
	    },
	    onFinalization : function(obj) {
	    }
	});
}

function InsertBBCode(u,v,textareaName)
{
    var oT = ById(textareaName);
    try {
        if (document.selection) {
                var str = document.selection.createRange().text;
                oT.focus();
                var sel = document.selection.createRange();
                sel.text = u + str + v;
        } else {
                var selLength = oT.textLength;
                var selStart = oT.selectionStart;
                var selEnd = oT.selectionEnd;
                var s1 = (oT.value).substring(0,selStart);
                var s2 = (oT.value).substring(selStart, selEnd);
                var s3 = (oT.value).substring(selEnd, selLength);
                oT.value = s1 + u + s2 + v + s3;
                oT.selectionStart = s1.length;
                oT.selectionEnd = s1.length + u.length + s2.length + v.length;
        }
        oT.value = ClearBBCodeDuplicates(oT.value);
        oT.focus();
        return;
    } catch(e) {}
}

function ClearBBCodeDuplicates(text)
{
    // usuwanie znacznikow bbcode o takiej samej nazwie
    // wystepujacych w bezposrednim sasiedztwie
    text = text.replace(/(\[([\w]*?)(=[\w\s]*?)\])\[\2.*?\]/g,'$1');
    text = text.replace(/\[(\/?[\w]*?)\]\[\1]/g,'[\$1]');
    return text;
}

function HideIfAllUnchk(to_hide_id, id_prefix, bIgnoreHidden) {
	inputs = document.getElementsByTagName('input');
	noInputs = inputs.length;

	hide = true;

	for(x=0; x<noInputs; x++) {

		input = inputs[x];

		if( !input.getAttribute('id') ) continue;

		if( input.getAttribute('type') == 'checkbox' && input.getAttribute('id').substr(0, id_prefix.length) == id_prefix && input.checked &&
			(input.style.display != 'none' || !bIgnoreHidden)) {
			hide = false;
			break;
		}

	}
	ById(to_hide_id).style.display = hide ? 'none' : '';
	//if( hide ) show(to_hide_id, 'none');
	//else show(to_hide_id, 'block');
}

function addAcceptEncodingToForms(forms) {
	for(i=0;i<forms.length;i++) {
		forms[i].setAttribute('accept-encoding', 'UTF-8');
	}
}

function getCookie(sName) {
    var sRE = "(?:; )?" + sName + "=([^;]*);?";
    var oRE = new RegExp(sRE);
    if (oRE.test(document.cookie)) {
        return decodeURIComponent(RegExp["$1"]);
    } else {
        return null;
    }
}

function setCookie(sName, sValue, oExpires, sPath, sDomain, bSecure)
{
    var sCookie = sName + "=" + encodeURIComponent(sValue);
    if (oExpires) {
        sCookie += "; expires=" + oExpires.toGMTString();
    }
    if (sPath) {
        sCookie += "; path=" + sPath;
    }
    if (sDomain) {
        sCookie += "; domain=" + sDomain;
    }
    if (bSecure) {
        sCookie += "; secure";
    }
    document.cookie = sCookie;
}

function deleteCookie(sName, sPath, sDomain)
{
    setCookie(sName,'',new Date(0), sPath, sDomain);
}

function TabRemember(tab_id) {
    tab_id = tab_id.replace(/.*?#(.*?)/,'$1');
    document.cookie = 'LastActiveTab=' + encodeURIComponent(tab_id);
}

function TabRemind() {
    var tab_id = getCookie('LastActiveTab');
    if (tab_id) {
        var oTab = ById(tab_id);
        if (oTab) {
            location.href = '#' + tab_id;
            deleteCookie('LastActiveTab');
        }
    }
}

function CheckboxAll(prefix) {
	inputs = document.getElementsByTagName('input');
	for(i=0; i<inputs.length; i++) {
		input = inputs[i];
		if( input.type == 'checkbox' ) {
			if( !prefix || input.id.substr(0,prefix.length)==prefix ) {
				if( input.checked != true ) {
					input.checked = true;
				} else {
					input.checked = false;
				}
			}
		}
	}
}


function SetMainCheckBox(formName, fieldName) {


	if(!document.forms[formName])
		return;
	var objCheckBox = eval('document.forms[formName].'+fieldName);
	if(!objCheckBox)
		return;

	if( objCheckBox.type == 'checkbox' ) {
		if( objCheckBox.checked == true ) {
			objCheckBox.checked= false;
		}
	}
}


function SelectUnselectAllCheckBoxes(prefixName, formName, fieldName) {

	var objCheckBox = eval('document.forms[formName].'+fieldName);

	objInputs = document.getElementsByTagName('input');

	for(i=0; i < objInputs.length; i++) {
		objInput = objInputs[i];
		if( objInput.type == 'checkbox' ) {
			if( !prefixName || objInput.id.substr(0,prefixName.length)==prefixName ) {
				if(objCheckBox.checked != false) {
					if( objInput.checked != true ) {
						objInput.checked = true;
					}
				}
				if(objCheckBox.checked == false) {
					if( objInput.checked == true ) {
						objInput.checked = false;
					}
				}

			}
		}
	}
}

function GetCursorPosition(e)
{
    if (!e) {
        var e = window.event
    }
    var oCursor = new Object();
    if (e.PageX || e.PageY) {
        oCursor.x = e.pageX;
        oCursor.y = e.pageY;
    } else {
        oCursor.x = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft - 90;
		oCursor.y = e.clientY + document.body.scrollTop + document.documentElement.scrollTop + 10;
    }
    // zatrzymanie przepływu zdarzenia
    e.cancelBubble = true;
	if (e.stopPropagation) {
        e.stopPropagation();
    }
    return oCursor;
}

// obsługa helpów w treści

var aOpenHelp = new Array(); // tablica id otwartych helpów

function CreateHelp(id)
{
    var oHelp = new Object();

    oHelp.Init = function(id)
    {
        var thisHelp = this;
        this.faq_item_id = id;
        // inicjuję obiekt xmlhttp
        this.XMLHTTP = createXmlHttpRequestObject();

        // dołączam słuchacza zdarzeń do guzika aktywującego helpa
        var element = ById('help_activator_' + id);
        element.onclick = function(e) {
            thisHelp.oCursor = GetCursorPosition(e);
            thisHelp.AO_Fetch();
        }
        if (element.captureEvents) {
            element.captureEvents(Event.CLICK);
        }
    }

    oHelp.AO_Fetch = function() {
        // zabezpieczenie przed wielokrotnym otwieraniem helpów
        if (aOpenHelp[id]) {
            return false;
        } else {
            aOpenHelp[id] = true;
        }
        // automatyczne zamknięcie
        window.setTimeout(CloseHelp, 30000);

        var state = this.XMLHTTP.readyState;
        var bReady = (state == 4) || (state == 0);
        if (bReady) {
            var thisHelp = this;
            var path = '/content/faq_item/' + this.faq_item_id + '/';
            this.XMLHTTP.open('GET', path, true);
            this.XMLHTTP.onreadystatechange = function() {
                thisHelp.AH_Fetch();
            }
            this.XMLHTTP.send(null);
        }
    }

    oHelp.AH_Fetch = function() {
        var XMLHTTP = this.XMLHTTP;
        if (XMLHTTP.readyState == 4) {
            if (XMLHTTP.status == 200) {
                this.Show(XMLHTTP.responseXML);
                document.body.style.cursor = 'default';
            }
        } else {
            document.body.style.cursor = 'progress';
        }
    }

    oHelp.Show = function(xml) {

        var root = xml.documentElement;
		var question = root.getElementsByTagName('question')[0].firstChild.nodeValue;
        var answer = root.getElementsByTagName('answer')[0].firstChild.nodeValue;
        answer = answer.replace(/\[url\=(.*?)\](.*?)\[\/url\]/g, '<a href="$1">$2</a>');
        answer = answer.replace(/\n/g, '<br />');

        var eHelpWrap = ById('help-wrap');

        var eHelpContainer = document.createElement('div');
        eHelpContainer.className = 'help-container';
        eHelpContainer.style.left = '' + this.oCursor.x + 'px';
        eHelpContainer.style.top = '' + this.oCursor.y + 'px';

        var eHelpExitButton = document.createElement('div');
        eHelpExitButton.className = 'help-exit-button';

        var eHelpTxt = document.createElement('div');
        eHelpTxt.className = 'help-txt';

		var help_template = '<span class="help-question">' + question + '</span>';
		help_template += '<span class="help-answer">' + answer + '</span>';

        eHelpTxt.innerHTML = help_template;

        var eHelpBottom = document.createElement('div');
        eHelpBottom.className = 'help-bottom';

        eHelpContainer.appendChild(eHelpExitButton);
        eHelpContainer.appendChild(eHelpTxt);
        eHelpContainer.appendChild(eHelpBottom);
        eHelpWrap.appendChild(eHelpContainer);

        var thisHelp = this;

        // dołączam słuchacza zdarzeń do guzika zamykającego helpa
        eHelpExitButton.onclick = function(e) {
            var oCursor = GetCursorPosition(e);
            eHelpContainer.parentNode.removeChild(eHelpContainer);
            aOpenHelp[thisHelp.faq_item_id] = false;
        }
        if (eHelpExitButton.captureEvents) {
            eHelpExitButton.captureEvents(Event.CLICK);
        }
    }

    oHelp.Init(id);

    return oHelp;
}

function HandleEscapeKey(e)
{
    e = (!e) ? window.event : e;
    code = (e.charCode) ? e.charCode : ((e.keyCode) ? e.keyCode : ((e.which) ? e.which : 0));
    if (code == 27) {
        if (oImageLayer.bIsOpen) {
            oImageLayer.Close();
        } else {
            ById('help-wrap').innerHTML = '<div style="position:absolute"></div>';
        }
    }
}

function CloseHelp()
{
	ById('help-wrap').innerHTML = '<div style="position:absolute"></div>';
    aOpenHelp = new Array();
}

function ViewEvents(div_id)
{
	var div_id = document.getElementById(div_id);

	if (div_id.style.display == 'none') {
		div_id.style.display = 'block';
	} else if (div_id.style.display == 'block') {
		div_id.style.display = 'none';
	}
}

function ViewLayer(div_id)
{
	var div_id = document.getElementById(div_id);

	if (div_id.style.display == 'none') {
		div_id.style.display = 'block';
	} else if (div_id.style.display == 'block') {
		div_id.style.display = 'none';
	}
}

history_rec_id = new Array();
forms = new Array();

function addBlankHistoryRecord(container_id) {

	if( history_rec_id[container_id] == undefined ) {
		history_rec_id[container_id] = 0;
	}

	container = ById(container_id);

	if( forms[container_id] == undefined ) {
		forms[container_id] = container.innerHTML;
	}

	formSchema = forms[container_id];

	if( container.style.display == 'none' ) {
		container.style.display = 'block';
		return true;
	}

	regexp = new RegExp('rec-id-[0-9]+', 'gim');
//	regexp2 = new RegExp('display: none', 'gim');

	history_rec_id[container_id]++;

    replaced = formSchema.replace(regexp, "rec-id-" + history_rec_id[container_id]);
//    replaced = replaced.replace(regexp2, "");

	container.innerHTML = container.innerHTML + replaced;
}

function GetProportionalSize(width, height, size, find)
{
    if (find == 'width') {
        return Math.floor((size * width) / height);
    } else {
        return Math.floor((size * height) / width);
    }
}

function ConfirmAction(text, url)
{
    if (confirm(text)) {
        location.href = url;
    }
}

function SpyCommentsSwitch(element_id, element_type)
{
    var oR = createXmlHttpRequestObject();
    var state = oR.readyState;
    var bReady = (state == 4) || (state == 0);
    if (bReady) {
        var path = '/community/spy_comments/' + element_id + '/' + element_type + '/';
        oR.open('GET', path, false);
        oR.send(null);
    }
}

function TrackedContentSwitch(content_type, content_id)
{
    var oAjax = new AjaxTool();
    var path = '/community/tracked_content/' + content_type + '/' + content_id + '/ajaxmode/';
    oAjax.MakeRequest('GET', path, null, 4);
    oAjax.ResponseHandler = function() {};
}


/**
* @desc Klasa zawierająca trochę przydatnych ogólnych funkcji.
*/
var oUtils = new function() {
    this.isObject = function (x) { return typeof x == "object" && x !== null; }
    this.isNumber = function (x) { return typeof x == "number"; }
    this.isArray = function (x) { return oUtils.isObject(x) && x.constructor == Array; }
    this.isBool = function (x) { return typeof x == "boolean"; }
    this.isString = function (x) { return typeof x == "string"; }
    this.isStringEmpty = function (x) { return (typeof x == "string") && (x == ""); }
    this.isUndefined = function (x) { return typeof x == "undefined"; }
    this.isUndefOrNull = function (x) { return typeof x == "undefined" || x === null; }
    this.isFunction = function (x) { return typeof x == "function"; }
    this.hide = function(obj) { ById(obj).style.display = 'none'; };
    this.show = function(obj) { alert(obj);ById(obj).style.display = 'block'; };
    this.setOpacity = function (aElement, aOpacity) {
        try { with (ById(aElement)) {
                aOpacity = parseFloat(parseInt(aOpacity * 100) / 100);
                if (window.ActiveXObject)
                     style.filter = "alpha(opacity="+(aOpacity * 100)+")";
                else style.opacity = aOpacity;
            }
        } catch (e) {}
    }
    this.getOpacity = function (aElement) {
        try {
            if (window.ActiveXObject)
                 return parseInt(ById(aElement).style.filter.match(/.*alpha\s*\(opacity\s*\=\s*([0-9]*).*/i)[1]) / 100;
            return parseFloat(oUtils.getStyleProp(ById(aElement), 'opacity'));
        } catch (e) { return 1; }
    }
    this.getStyleProp = function (element, property) {
        var el = ById(element), value;
        if (el.currentStyle)
            var value = el.currentStyle[property];
        else if (window.getComputedStyle)
            var value = document.defaultView.getComputedStyle(el, null).getPropertyValue(property);
        return value;
    }
    this.centerObject = function (wnd, bFixed) {
        wnd = ById(wnd);
        if (!wnd) return;
        oUtils.centerObjectH(wnd, bFixed);
        oUtils.centerObjectV(wnd, bFixed);
    };
    this.centerObjectV = function (wnd, bFixed){
        wnd = ById(wnd); if (!wnd) return;
        var x = Math.floor((oUtils.getDocumentDims().w  - wnd.offsetWidth)  / 2);
        wnd.style.left = ((x < 0) ? 0 : x) + (bFixed ? 0 : oUtils.getDocumentScroll().x) + "px";
    };
    this.centerObjectH = function (wnd, bFixed) {
        wnd = ById(wnd); if (!wnd) return;
        var y = Math.floor((oUtils.getDocumentDims().h - wnd.offsetHeight) / 2);
        wnd.style.top  = ((y < 0) ? 0 : y) + (bFixed ? 0 : oUtils.getDocumentScroll().y)  + "px";
    };
    this.getDocumentDims = function () {
        if (self.innerWidth) {
            return { w : self.innerWidth, h : self.innerHeight }
        } else if (document.documentElement && document.documentElement.clientWidth) {
            return { w : document.documentElement.clientWidth, h : document.documentElement.clientHeight }
        } else if (document.body) {
            return { w : document.body.clientWidth, h : document.body.clientHeight }
        } return { w : 0, h : 0 }
    };
    this.getDocumentScroll = function (){
        var scrOfX = 0, scrOfY = 0;
        if( typeof( window.pageYOffset ) == 'number' ) {
            return { y : window.pageYOffset, x : window.pageXOffset }
        } else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
            return { y : document.body.scrollTop, x : document.body.scrollLeft }
        } else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
            return { y : document.documentElement.scrollTop, x : document.documentElement.scrollLeft }
        } return { x : 0, y : 0 }
    };
    this.moveSelectedOptions = function(oSource, oDestination, oCallbackOnMove) {
        for (var i = oSource.options.length-1; i >= 0; i--) {
            if (oSource.options[i].selected) {
                if (typeof oCallbackOnMove == 'function')
                    if (!oCallbackOnMove(i, oSource, oDestination)) continue;
                oDestination.options[oDestination.options.length] = new Option(oSource.options[i].text, oSource.options[i].value);
                oSource.options[i] = null;
            }
        }
    };
    this.dockToObject = function(oDockedObject, oTarget, iDockedObjectCorner, iTargetCorner, iDeltaX, iDeltaY) {
        oDockedObject = ById(oDockedObject);
        oTarget = ById(oTarget);
        if (iDockedObjectCorner < 1 || iDockedObjectCorner > 4)
            iDockedObjectCorner = 1;
        if (iTargetCorner < 1 || iTargetCorner > 4)
            iTargetCorner = 1;
        var iTargetX = this.getElementX(oTarget),
            iTargetY = this.getElementY(oTarget),
            iDX = (iDockedObjectCorner % 2) ? 0 : -oDockedObject.offsetWidth,
            iDY = (iDockedObjectCorner <= 2) ? 0 : -oDockedObject.offsetHeight;
        iTargetX += (iTargetCorner % 2) ? 0 : oTarget.offsetWidth;
        iTargetY += (iTargetCorner <= 2) ? 0 : oTarget.offsetHeight;
        oDockedObject.style.left = (iTargetX + iDX + (isNaN(iDeltaX) ? 0 : iDeltaX)) + 'px';
        oDockedObject.style.top = (iTargetY + iDY + (isNaN(iDeltaY) ? 0 : iDeltaY)) + 'px';
    };
    this.getElementX = function (obj, endObject) {
        var curleft = 0;
        if (obj.offsetParent) {
            while (obj.offsetParent && obj != endObject) {
                curleft += obj.offsetLeft;
                obj = obj.offsetParent;
            }
        } else if (typeof obj.x != "undefined") curleft += obj.x;
        return curleft;/* + (is_ie ? 12 : 0);*/
    };
    this.getElementY = function (obj, endObject) {
        var curtop = 0;
        if (obj.offsetParent) {
            while (obj.offsetParent && obj != endObject) {
                curtop += obj.offsetTop;
                obj = obj.offsetParent;
            }
        } else if (typeof obj.y != "undefined") curtop += obj.y;
        return curtop;/* + (is_ie ? 17 : 0);*/
    };
    this.createXMLDoc = function(sXML) {
        try {
            if (window.ActiveXObject) {
                var oXMLDoc = new ActiveXObject("Microsoft.XMLDOM");
                oXMLDoc.async = "false";
                oXMLDoc.loadXML(sXML);
                return oXMLDoc;
            }
            else return (new DOMParser()).parseFromString(sXML, "text/xml");
        }
        catch (e) { return false; }
    };
    this.xpath = function(sXPath, oXMLDocument) {
        if (typeof oXMLDocument == 'string')
            oXMLDocument = this.createXMLDoc(oXMLDocument);
        if (document.evaluate) {
            var oResult = oXMLDocument.evaluate(sXPath, oXMLDocument, null, XPathResult.TYPE_ANY, null);
        } else {
            oXMLDocument.setProperty("SelectionLanguage", "XPath");
            var oResult = oXMLDocument.selectNodes(sXPath);
        }

        try {
            var aResult = [];
            if (document.evaluate) {
                var oNode = oResult.iterateNext();
                while (oNode) {
                    aResult.push(oNode);
                    oNode = oResult.iterateNext();
                }
            }
            else {
                for (var i = 0; i < oResult.length; i++) {
                    aResult.push(oResult[i]);
                }
            }
        } finally { return aResult; }
    };
    this.bubbleEvent = function (aEvent, aBubble) {
        if (!aEvent) if (!(aEvent = window.event)) return;
        aEvent.cancelBubble = !aBubble;
        if (aEvent.stopPropagation && !aBubble) aEvent.stopPropagation();
    };
    this.getXMLNodeText = function(node) {
        var text = node.textContent || node.text || node.innerText; return text ? text : '';
    };
    this.getWindowInnerH = function () { return window.innerHeight ? window.innerHeight : window.document.documentElement.clientHeight; };
    this.getWindowInnerW = function () { return window.innerWidth ? window.innerWidth : window.document.documentElement.clientWidth; };
    this.getSiteH = function () { return Math.max(Math.max(window.document.body.offsetHeight, window.innerHeight ? window.innerHeight : window.document.documentElement.clientHeight), window.document.documentElement.scrollHeight); };
    this.getSiteW = function () { return Math.max(window.innerWidth ? window.innerWidth : window.document.documentElement.clientWidth, window.document.documentElement.scrollWidth); };
}
/**
* @desc Klasa pomocna przy różnych efektach na stronie.
*/
var oTransformations = new function() {
    this._transformValueThreads = [];
    this._transformElementAlphaSetFunc = function (aThread) {
        oUtils.setOpacity(aThread['id'], aThread['value']);
    };
    this._transformValue = function (aThreadName) {
        var thread = this._transformValueThreads[aThreadName];
        if (!(oUtils.isObject(thread) && thread.constructor == Array)) return;
        if (typeof thread['setfunc'] != "function") return;
        if (thread['value'] < thread['limit']) {
            if ((thread['value'] += thread['step']) >= thread['limit']) {
                thread['value'] = thread['limit'];
                thread['setfunc'](thread);
                if (typeof thread['callback'] == 'function')
                    this._transformValueCallback(aThreadName);
                return;
            }
        } else {
            if ((thread['value'] -= thread['step']) <= thread['limit']) {
                thread['value'] = thread['limit'];
                thread['setfunc'](thread);
                if (typeof thread['callback'] == 'function')
                    this._transformValueCallback(aThreadName);
                return;
            }
        }
        thread['setfunc'](thread);
        thread['timer'] = setTimeout("oTransformations._transformValue('"+aThreadName+"')", thread['interval']);
    };
    this._transformValueCallback = function (aThreadName) {
        try {
            if (oUtils.isObject(this._transformValueThreads[aThreadName]) && this._transformValueThreads[aThreadName].constructor == Array)
                if (typeof this._transformValueThreads[aThreadName]['callback'] == "function")
                    this._transformValueThreads[aThreadName]['callback'](this._transformValueThreads[aThreadName]);
        } finally {
            delete this._transformValueThreads[aThreadName];
        }
    };
    this.transformValue = function (aThreadName, aValue, aLimit, aStep, aInterval, aCallback, aSetFunc, aUserData) {
        var thread = false;
        if (oUtils.isArray(this._transformValueThreads[aThreadName])) {
            clearTimeout(this._transformValueThreads[aThreadName]['timer']);
            thread = this._transformValueThreads[aThreadName];
        } else {
            thread = [];
            this._transformValueThreads[aThreadName] = thread;
        }
        thread['id'] = aThreadName; thread['value'] = parseInt(aValue);
        thread['timer'] = 0; thread['step'] = aStep; thread['limit'] = aLimit;
        thread['interval'] = aInterval; thread['callback'] = aCallback;
        thread['userdata'] = aUserData; thread['setfunc'] = aSetFunc;
        this._transformValue(aThreadName);
    };
    this.abortTransformation = function (aThreadName) {
        if (oTransformations._transformValueThreads[aThreadName]) {
            clearTimeout(oTransformations._transformValueThreads[aThreadName]['timer']);
            delete oTransformations._transformValueThreads[aThreadName];
        }
    };
    this.transformElementAlpha = function (aElement, aStep, aLimit, aInterval, aCallback, aUserData) {
        this.transformValue(aElement, oUtils.getOpacity(aElement), aLimit, aStep, aInterval, aCallback, this._transformElementAlphaSetFunc, aUserData) ;
    };
    this.isThreadActive = function(aThreadName) {
        return (typeof oTransformations._transformValueThreads[aThreadName] == "undefined") ? false : true;
    };
}
function getElementsByClass( searchClass, domNode, tagName) {
	if (domNode == null) domNode = document;
	if (tagName == null) tagName = '*';
	var el = new Array();
	var tags = domNode.getElementsByTagName(tagName);
	var tcl = " "+searchClass+" ";
	for(i=0,j=0; i<tags.length; i++) {
		var test = " " + tags[i].className + " ";
		if (test.indexOf(tcl) != -1)
			el[j++] = tags[i];
	}
	return el;
}
var oInvitations = new function() {
    this._iTypes = {CONTACT_INNER: 1, CONTACT_OUTER: 2, GROUP_INNER: 3, GROUP_OUTER: 4, EVENT_INNER: 5};
    this._bInitialized = false;
    this._oPreLoader = false;
    this._prepareAjaxParams = function(oParams) {oParams.onInitialization = oInvitations.setBusyOn; oParams.onFinalization = oInvitations.setBusyOff; oParams.disableForm = false;};
    this._ajaxPost = function(oParams) { this._prepareAjaxParams(oParams); return advAJAX.post(oParams); };
    this._ajaxGet = function(oParams) { this._prepareAjaxParams(oParams); return advAJAX.get(oParams); };
    this._ajaxSubmit = function(oForm, oParams){ this._prepareAjaxParams(oParams); return advAJAX.submit(oForm, oParams); };
    this._staticContent = '';
    this.setBusyOn = function() {
        if (!oPopupWindow.isVisible()) {
            oPopupWindow.showLoader();
            return;
        }
        if (!oInvitations._oLoader) return;
        oInvitations._oLoader.style.display = 'block';
        oInvitations._oLoader.style.width = (oInvitations._oWindow.offsetWidth > 1 ? oInvitations._oWindow.offsetWidth-2 : 0) + 'px';
        oInvitations._oLoader.style.height = (oInvitations._oWindow.offsetHeight > 1 ? oInvitations._oWindow.offsetHeight-2 : 0) + 'px';
        oInvitations._oLoader.style.top = oInvitations._oWindow.offsetTop + 'px';
        oInvitations._oLoader.style.left = oInvitations._oWindow.offsetLeft + 'px';
    };
    this.setBusyOff = function(){
        if (!oInvitations._oLoader) return;
        oInvitations._oLoader.style.display = 'none';
    };
    this._init = function(oContainer) {
        if (this._bInitialized) return true;
        if (!oContainer) {
            this._ajaxPost({
                url: '/inv/ajax_invite/',
                async: false
            });
            oPopupWindow.setWindowContent(window.advajax_obj.xmlHttpRequest.responseText);
            var oScripts = oPopupWindow.getWindowNode().getElementsByTagName('script');
            for (var i in oScripts) if (oScripts[i] && oScripts[i].innerHTML) { window.eval(oScripts[i].innerHTML); }
        }
        this._oWindow = ById('invite_window');
        this._oLoader = ById('invite_window_loader');
        oInvitations._bInitialized = oUtils.isUndefOrNull(this._oWindow) ? false : true;
        this.setBusyOff();
        return this._bInitialized;
    };
    this.inviteContactInner = function(iReceiverId) {
        this.setBusyOn();
        if (!this._init()) return;
        this._loadForm(this._iTypes.CONTACT_INNER, { 'r_profile_id' : iReceiverId });
        this.setBusyOff();
        this._showWindow();
    };
    this.inviteContactOuter = function() {
        this.setBusyOn();
        if (!this._init()) return;
        this._loadForm(this._iTypes.CONTACT_OUTER, {});
        this.setBusyOff();
        this._showWindow();
    };
    this.inviteGroupInner = function(iGroupId, iReceiverId) {
        this.setBusyOn();
        if (!this._init()) return;
        this._loadForm(this._iTypes.GROUP_INNER, { 'target_id' : iGroupId, "r_profile_id": (iReceiverId ? iReceiverId : 0) });
        this.setBusyOff();
        this._showWindow();
    };
    this.inviteGroupOuter = function(iGroupId) {
        this.setBusyOn();
        if (!this._init()) return;
        this._loadForm(this._iTypes.GROUP_OUTER, { 'target_id' : iGroupId });
        this.setBusyOff();
        this._showWindow();
    };
    this.inviteEventInner = function(iEventId, iReceiverId) {
        this.setBusyOn();
        if (!this._init()) return;
        this._loadForm(this._iTypes.EVENT_INNER, { 'target_id' : iEventId, "r_profile_id": (iReceiverId ? iReceiverId : 0) });
        this.setBusyOff();
        this._showWindow();
    };
    this.setStaticContent = function(sContent) {
        if (typeof sContent == 'string') this._staticContent = sContent;
        if (ById('invite_window_static_content')) ById('invite_window_static_content').innerHTML = this._staticContent;
    };
};

function switchOctopusAdvert(iStatus, oAdvertContainer)
{
    if (oAdvertContainer && !iStatus)
        oAdvertContainer.parentNode.removeChild(oAdvertContainer);
    advAJAX.get({ url: '/misc/switch_octopus_advert/' + parseInt(iStatus) });
}

var oIFrameAjax = new function() {
    var _fCallback = false, _bIsLoading = false, _xUserData = null, _oFrameData = {
            sId : 'iframe-ajax', oContainer : false, oFrame : false, oFrameDoc : false
        };
    var _initialize = function()
    {
        _oFrameData.oContainer = ById(_oFrameData.sId) ? ById(_oFrameData.sId) : document.createElement("div");
        _oFrameData.oContainer.id = _oFrameData.sId;
        with (_oFrameData.oContainer.style) {
            position = "absolute";
            top = left = "-9999px";
            width = height = "0px";
        }
        if (_oFrameData.oContainer.parentNode != document.body) {
            document.body.appendChild(_oFrameData.oContainer);
            _oFrameData.oContainer.innerHTML =
                '<iframe src="about:blank" onload="oIFrameAjax._onLoad(false);" onreadystatechange="oIFrameAjax._onLoad(true)"'+
                ' name="' + _oFrameData.sId + '_frame" id="' + _oFrameData.sId + '_frame"'+
                '></iframe>';
        }
        // a fix for opera
        _oFrameData.oFrame = ById(_oFrameData.sId + "_frame");
        var oFrameDoc = _oFrameData.oFrame.contentDocument ? _oFrameData.oFrame.contentDocument  : (_oFrameData.oFrame.contentWindow ? _oFrameData.oFrame.contentWindow.document : _oFrameData.oFrame.document);
        if (oFrameDoc.body)
            oFrameDoc.body.innerHTML = '__content__not__loaded__yet__';
        return true;
    };
    this.sendForm = function(aForm, aURL, aMethod, aCallback, aUserData) {
        var oSrcForm = ById(aForm);
        if (_bIsLoading || !oSrcForm || !_initialize())
            return false;
        _bIsLoading = true;
        oSrcForm.target = _oFrameData.sId + "_frame";
        oSrcForm.action = aURL;
        oSrcForm.enctype = "multipart/form-data";
        oSrcForm.method = aMethod == "get" ? "get" : "post";
        _xUserData = aUserData;
        _fCallback = aCallback;
        oSrcForm.submit();
        return true;
    };
    this.send = function(aURL, aMethod, aCallback, aUserData) {
        if (_bIsLoading || !_initialize())
            return false;
        _bIsLoading = true;
        _xUserData = aUserData;
        _fCallback = aCallback;
        _oFrameData.oFrame.src = aURL;
        return true;
    };
    this._onLoad = function(aIsStateEvent) {
        if (!_bIsLoading || aIsStateEvent) return; //|| _oFrameData.oFrame.readyState != "complete"
        var oFrameDoc = _oFrameData.oFrame.contentDocument ? _oFrameData.oFrame.contentDocument  : (_oFrameData.oFrame.contentWindow ? _oFrameData.oFrame.contentWindow.document : _oFrameData.oFrame.document),
            responseText = oFrameDoc.body.textContent || oFrameDoc.body.text || oFrameDoc.body.innerText || '';
        // opera fix
        if (responseText == "__content__not__loaded__yet__") {
            setTimeout("oIFrameAjax._onLoad(false)", 250);
            return;
        }
        _bIsLoading = false;
        if (typeof _fCallback == 'function')
            _fCallback(oFrameDoc.body.innerHTML, _xUserData);
    };
};
function isParentOf(oParent, oElement) {
    var oElementParent = oElement.parentNode;
    while (oElementParent) {
        if (oElementParent === oParent) return true;
        oElementParent = oElementParent.parentNode;
    }
    return false;
}
function toggleComboBoxes(bShow, oExcludedContainer) {
    if (window.XMLHttpRequest) return; /** enabled only for old browsers like IE6 */
    /*var iIEVersion = parseFloat(navigator.appVersion.split("MSIE")[1]);
    if (iIEVersion > 6) return;*/
    var aElements = document.getElementsByTagName('select');
    for (var i = 0; i < aElements.length; i++) {
        if (aElements[i].tagName && aElements[i].tagName.toLowerCase() == 'select') {
            var oElement = aElements[i];
            if (oExcludedContainer && isParentOf(oExcludedContainer, oElement)) continue;
            if (typeof oElement._defaultVisibility == 'undefined') {
                oElement._defaultVisibility = oElement.style.visibility;
                oElement._defaultVisibilityOnShow = bShow;
                oElement.style.visibility = bShow ? 'visible' : 'hidden';
            } else {
                oElement.style.visibility = (oElement._defaultVisibilityOnShow != bShow) ? oElement._defaultVisibility : (bShow ? 'visible' : 'hidden');
            }
        }
    }
}

var oGlobalEvents = new function() {
    this.mousePos = { x: null, y: null };
    var _oEvents = {
        'click'     : { handlers : [], next_id : 0 },
        'mousemove' : { handlers : [], next_id : 0 },
        'mouseup'   : { handlers : [], next_id : 0 },
        'mousedown' : { handlers : [], next_id : 0 },
        'scroll'    : { handlers : [], next_id : 0 },
        'bdlclick'  : { handlers : [], next_id : 0 },
        'blur'      : { handlers : [], next_id : 0 },
        'keypress'  : { handlers : [], next_id : 0 },
        'keydown'   : { handlers : [], next_id : 0 },
        'keyup'     : { handlers : [], next_id : 0 },
        'load'      : { handlers : [], next_id : 0 }
    };
    this.events = _oEvents;
    var _findHandler = function(fHandler, sEventType) {
        if (!_oEvents[sEventType])
            return false;
        var aHandlers = _oEvents[sEventType].handlers;
        for (var iIndex in aHandlers)
            if (aHandlers[iIndex].handler === fHandler)
                return aHandlers[iIndex];
        return false;
    };
    this.attachHandler = function (sEventType, fHandler, xUserData, sHandlerId) {
        sEventType = sEventType.toLowerCase();
        if (typeof _oEvents[sEventType] == 'undefined')
            return false;
        var oEvent = _oEvents[sEventType],
            oHandler = _findHandler(fHandler, sEventType);
        if (oHandler) return true;
        var xId = (typeof sHandlerId == 'string') ? sHandlerId : oEvent.next_id++;
        oEvent.handlers[xId] = {
            id : xId,
            handler : fHandler,
            userdata : xUserData
        };
        return xId;
    };
    this.detachHandler = function (sEventType, fHandler) {
        sEventType = sEventType.toLowerCase();
        if (typeof _oEvents[sEventType] == 'undefined')
            return false;
        var aHandlers = _oEvents[sEventType].handlers;
        for (var xId in aHandlers)
            if (aHandlers[xId].handler === fHandler)
                delete aHandlers[xId];
    };
    this.detachHandlerById = function (sEventType, sHandlerId) {
        sEventType = sEventType.toLowerCase();
        if (typeof _oEvents[sEventType] == 'undefined')
            return false;
        delete _oEvents[sEventType].handlers[sHandlerId];
    };
    var _onMouseMove = function (oEvent)
    {
        if (!oEvent) var oEvent = window.event;
        if (oEvent.pageX || oEvent.pageY) {
            oGlobalEvents.mousePos.x = oEvent.pageX;
            oGlobalEvents.mousePos.y = oEvent.pageY;
        } else if (oEvent.clientX || oEvent.clientY) {
            var docScroll = oUtils.getDocumentScroll();
            oGlobalEvents.mousePos.x = oEvent.clientX + docScroll.x;
            oGlobalEvents.mousePos.y = oEvent.clientY + docScroll.y;
        }
        oEvent.cancelBubble = true;
        if (oEvent.stopPropagation)
            oEvent.stopPropagation();
        _onEvent(oEvent, 'mousemove');
    };
    var _onEvent = function (oEvent, sEventType) {
        if (!_oEvents[sEventType]) return;
        //oUtils.bubbleEvent(oEvent, false);
        var aHandlers = _oEvents[sEventType].handlers;
        for (var hId in aHandlers)
            try {
                if (typeof aHandlers[hId].handler == 'function')
                    aHandlers[hId].handler(oEvent, aHandlers[hId].userdata);
            } catch (e) { continue; }
    };
    window.document.onmousemove = _onMouseMove;
    window.document.onmouseup   = function(oEvent) { _onEvent(oEvent, 'mouseup'); };
    window.document.onmousedown = function(oEvent) { _onEvent(oEvent, 'mousedown'); };
    window.document.onclick     = function(oEvent) { _onEvent(oEvent, 'click'); };
    window.onscroll             = function(oEvent) { _onEvent(oEvent, 'scroll'); };
    window.document.ondblclick  = function(oEvent) { _onEvent(oEvent, 'dblclick'); };
    window.onblur               = function(oEvent) { _onEvent(oEvent, 'blur'); };
    window.onkeypress           = function(oEvent) { _onEvent(oEvent, 'keypress'); };
    window.onkeyup              = function(oEvent) { _onEvent(oEvent, 'keyup'); };
    window.onkeydown            = function(oEvent) { _onEvent(oEvent, 'keydown'); };
    window.onload               = function(oEvent) { _onEvent(oEvent, 'load'); };
};

function sprintf(sFormat) {
    for (i = 1; i < arguments.length; i++)
        sFormat = sFormat.replace('%s', arguments[i]);
    return sFormat;
};

var oPopupWindow = new function()
{
    var _that = this,
        _oComponents = {
            container : false,
            blocker : false,
            loader : false,
            window : false,
            blockerTimer : 0
        };

    this.onbeforeshow = false;
    this.onaftershow = false;
    this.onbeforehide = false;
    this.onafterhide = false;

    var _initialize = function()
    {
        if (_oComponents.window) return true;
        _oComponents.container = document.createElement('div');
        _oComponents.window = document.createElement('div');
        _oComponents.blocker = document.createElement('div');
        _oComponents.loader = document.createElement('div');

        _oComponents.container.className = 'popup-container';
        _oComponents.window.className = 'popup-window';
        _oComponents.blocker.className = 'popup-blocker';
        _oComponents.loader.className = 'popup-loader';

        _oComponents.loader.innerHTML = '<img src="/_p/img/ajax-loader.gif" />';

        _oComponents.container.appendChild(_oComponents.blocker);
        _oComponents.container.appendChild(_oComponents.window);
        _oComponents.container.appendChild(_oComponents.loader);

        document.body.appendChild(_oComponents.container);

        return true;
    };
    this.showBlocker = function()
    {
        if (!_initialize()) return;
        with (_oComponents.blocker.style) {
             display = "block";
             width = "100%";
             height = oUtils.getSiteH() + "px";
        }
        toggleComboBoxes(false, _oComponents.window);
        clearInterval(_oComponents.blockerTimer);
        _oComponents.blockerTimer = setInterval('oPopupWindow.showBlocker()', 400);
    };
    this.hideBlocker = function()
    {
        if (!_initialize()) return;
        _oComponents.blocker.style.display = "none";
        toggleComboBoxes(true, _oComponents.window);
        clearInterval(_oComponents.blockerTimer);
    };
    this.showLoader = function(bNoBlocker)
    {
        if (!_initialize()) return;
        if (!bNoBlocker) _that.showBlocker();
         _oComponents.loader.style.display = "block";
         oUtils.centerObject(_oComponents.loader);
    };
    this.hideLoader = function()
    {
        if (!_initialize()) return;
        _oComponents.loader.style.display = "none";
    };
    this.showWindow = function(iWidth, sContent, bNoBlocker)
    {
        if (typeof this.onbeforeshow == 'function' && this.onbeforeshow()) return;
        if (!_initialize()) return;
        if (_oComponents.blocker.style.display != 'block' && !bNoBlocker)
            _that.showBlocker();
        _oComponents.window.style.width = iWidth;
        _oComponents.window.style.display = "block";
        if (sContent !== null) _oComponents.window.innerHTML = sContent;
        oUtils.centerObject(_oComponents.window);
        if (typeof this.onaftershow == 'function') this.onaftershow();
    };
    this.hideWindow = function(bLeaveBlocker)
    {
        if (typeof this.onbeforehide == 'function' && this.onbeforehide()) return;
        if (!_initialize()) return;
        if (!bLeaveBlocker)
            _that.hideBlocker();
        _oComponents.window.style.display = "none";
        if (typeof this.onafterhide == 'function') this.onafterhide();
    };
    this.setWindowContent = function(sContent)
    {
        if (!_initialize()) return;
        _oComponents.window.innerHTML = sContent;
    };
    this.getWindowNode = function()
    {
        if (!_initialize()) return false;
        return _oComponents.window;
    };
    this.centerWindow = function()
    {
        if (!_initialize()) return false;
        oUtils.centerObject(_oComponents.window);
    };
    this.isVisible = function()
    {
        if (!_initialize()) return false;
        return _oComponents.window.style.display == "block" ? true : false;
    };
};

var Pages = function(oConfig)
{
    var _that = this,
        _oContainer = ById(oConfig.container),
        _oConfig = {
            bSwitchByClass : oConfig.switchByClass ? true : false,
            aClasses : oUtils.isArray(oConfig.classes) ? oConfig.classes : [],
            fOnBeforeSwitch : oConfig.onBeforeSwitch,
            fOnAfterSwitch : oConfig.onAfterSwitch
        },
        _aPages = [],
        _iCurrentPage = 0;

    this._getPages = function() {
        var aPages = [];
        for (var i = 0; i < _oContainer.childNodes.length; i++) {
            if (_oContainer.childNodes.item(i).nodeType == 1)
                aPages.push({ node : _oContainer.childNodes.item(i), index : i, number : i+1 });
        }
        return aPages;
    };

    this._getCurrentPageIndex = function() {
        for (var i in _aPages) {
            if (_oConfig.bSwitchByClass)
                 if (_aPages[i].node.className == _oConfig.aClasses[0]) return i;
            else if (_aPages[i].node.style.display != 'none') return i;
        }
        return 0;
    };

    this._togglePage = function(iPage, bShow) {
        if (_aPages[iPage]) {
            if (_oConfig.bSwitchByClass)
                 _aPages[iPage].node.className = _oConfig.classes[bShow ? 0 : 1];
            else _aPages[iPage].node.style.display = bShow ? 'block' : 'none';
        }
    };

    this._validatePageIndex = function(iPageIndex) {
        if (iPageIndex < 0) iPageIndex = 0;
        if (iPageIndex > _aPages.length - 1) iPageIndex = _aPages.length - 1;
        return iPageIndex;
    };

    this.goTo = function(iPageIndex) {
        iPageIndex = this._validatePageIndex(iPageIndex);

        if (typeof _oConfig.fOnBeforeSwitch == 'function') {
            var iNewPage = _oConfig.fOnBeforeSwitch(iPageIndex, _iCurrentPage, _aPages);
            if (iNewPage == -1) return;
            iPageIndex = this._validatePageIndex(iNewPage);
        }
        this._togglePage(_iCurrentPage, false);
        this._togglePage(iPageIndex, true);

        if (typeof _oConfig.fOnAfterSwitch == 'function')
            _oConfig.fOnAfterSwitch(iPageIndex, _iCurrentPage, _aPages);
        _iCurrentPage = iPageIndex;
    };

    this.next = function() {
        this.goTo(_iCurrentPage + 1);
    };

    this.prev = function() {
        this.goTo(_iCurrentPage - 1);
    };

    this.currentPage = function() {
        return _iCurrentPage;
    };

    _aPages = this._getPages();
    _iCurrentPage = this._getCurrentPageIndex();
};

var oProfeoValidator = new function() {
	this.ValidLength = function(text, min, max) {
		text = text.trim();
		var textLength = text.length;
		if(min) {
			if(textLength < min)
				return false;
		}
		if(max) {
			if(textLength > max)
				return false;
		}
		return true;
	};

	this.isEmpty = function(text) {
		return (text.trim() == '') ?  true : false;
	};

    this.isNumber = function(number) {
        return /^([-]?)(0|([1-9]{1}[0-9]*))([\.,]{1}[0-9]+)?$/.test(number);
    };

	this.isNumeric = function(number) {
		return /^[0-9]+$/.test(number);
	};

    this.isPositiveNumber = function(number) {
        return oProfeoValidator.isNumber(number) && number > 0;
    };

    this.isEmail = function(email) {
        return /^[0-9a-z]([+-_.]?[0-9a-z])*@[0-9a-z]([-.]?[0-9a-z])*\.[a-z]{2,10}$/i.test(email);
    };

    this.isURL = function(url, noProtocolValidation) {
        if (noProtocolValidation)
            return /^(?:([a-z][-+.a-z0-9]*):)?(?:(?:\/\/)?(?:((?:%[0-9a-f]{2}|[-a-z0-9_.!~*\'\(\);:\&=+$,])*)@)?(?:((?:[a-z0-9](?:[-a-z0-9]*[a-z0-9])?\.)*[a-z](?:[a-z0-9]+)?\.?)|([0-9]{1,3}(?:\.[0-9]{1,3}){3}))(?::([0-9]*))?)((?:\/(?:%[0-9a-f]{2}|[-a-z0-9_.!~*\'():@\&=+$,;])*)*\/?)?(?:\?([^#]*))?(?:\#((?:%[0-9a-f]{2}|[-a-z0-9_.!~*\'();\/?:@\&=+$,])*))?$/i.test(url);
        return /^(?:([a-z][-+.a-z0-9]*):)?(?:\/\/(?:((?:%[0-9a-f]{2}|[-a-z0-9_.!~*\'();:\&=+$,])*)@)?(?:((?:[a-z0-9](?:[-a-z0-9]*[a-z0-9])?\.)*[a-z](?:[a-z0-9]+)?\.?)|([0-9]{1,3}(?:\.[0-9]{1,3}){3}))(?::([0-9]*))?)((?:\/(?:%[0-9a-f]{2}|[-a-z0-9_.!~*\'():@\&=+$,;])*)*\/?)?(?:\?([^#]*))?(?:\#((?:%[0-9a-f]{2}|[-a-z0-9_.!~*\'();\/?:@\&=+$,])*))?$/i.test(url);
    };

    this.isPhoneNumber = function(phone) {
        return /^\+?[\d\s]+$/.test(phone);
    };

    this.isNIP = function(nip) {
        if ((nip = nip.trim()).length)
        {
            var weights = [6, 5, 7, 2, 3, 4, 5, 6, 7],
                nip = nip.replace(/[\s-]/g, '', nip),
                sum = 0;

            if (nip.length != 10 || !this.isNumeric(nip))
                return false;

            for (var x = 0; x <= 8; x++) {
                sum += parseInt(nip.charAt(x)) * weights[x];
            }

            return (sum % 11) == nip.charAt(9);
        }
        return false;
    };

	this.isREGON = function(regon) {
        if ((regon = regon.trim()).length != 9 || !this.isNumeric(regon))
            return false;

        var aSteps = [8, 9, 2, 3, 4, 5, 6, 7],
            iSum = 0;
        for (var i = 0; i < 8; i++) {
            iSum += aSteps[i] * parseInt(regon.charAt(i));
        }

        if ((((iSum % 11) == 10) ? 0 : (iSum % 11)) == regon.charAt(8))
            return true;
        return false;
	};
};

function initializeTitleClouds() {
    var aElements = document.body.getElementsByTagName('a'), a;
    for (i = 0; i < aElements.length; i++) {
        a = aElements[i];
        if (a.title) {
            with (a.t = document.createElement('div')) {
                id = 'view_info';
                style.zIndex = '999999999';
                innerHTML = a.title.replace(/\|/g,'');
            }
            a.onmouseover = function(e) {
                this.title = '';
                this.onmousemove(e)
                document.body.appendChild(this.t);
            }
            a.onmouseout = function(x) {
                this.title = this.t.innerHTML.replace(/<br \/>/g,"\|");
                this.t.parentNode.removeChild(this.t);
            }
            a.onmousemove = function(e) {
                e = e||event;
                with(this.t.style) {
                    left = e.clientX+(document.documentElement.scrollLeft||document.body.scrollLeft)+'px';
                    top = e.clientY+(document.documentElement.scrollTop||document.body.scrollTop)+'px';
                }
            }
        }
    }
}
function addEvent(O, E, F, x) {
    return (x=O.addEventListener)? x(E,F,1):(x=O.attachEvent) ? x('on'+E,F) :! 1;
}

addEvent(window, 'load', initializeTitleClouds);

function FCKeditor_OnComplete( aInstance )
{
   aInstance.AttachToOnSelectionChange(function(aEditorInstance) { aEditorInstance.UpdateLinkedField(); } );
}