/*
 * $Id: ty_core.js.php 11355 2009-07-07 14:46:18Z sseitz $
 */

/**
 * page reload
 */
var ty_aj_canreload = true;

function ty_aj_pagereload() {
    if (ty_aj_canreload==true) {
		ty_aj_canreload=false;
		document.location.reload();
	}
}

/**
 * generic ajax action
 */
var ty_aj_callback_disabled=false;

var ty_aj_succeed = new Object();

function ty_aj_action(key,selfvalue,postreload) {
	var scriptElem = document.createElement('script');
	if (scriptElem) {
		ty_aj_succeed[key]=postreload;
		if ((!selfvalue)||(selfvalue=='undefined')) selfvalue='';
        //scriptElem.setAttribute('src','/js/ty_aj_'+key+'_'+escape(selfvalue)+'.js');
        scriptElem.setAttribute('src','/js/ty_aj_'+key+'_'+ty_base64Encode(selfvalue)+'.js');
		scriptElem.setAttribute('type','text/javascript');
		scriptElem.setAttribute('charset','utf-8');
		document.getElementsByTagName('head')[0].appendChild(scriptElem);
	}
}

/**
 * xml deserializer and serializer
 */
function ty_parsexml(string) {
	if (document.implementation.createDocument) {
		var parser = new DOMParser();
		var doc = parser.parseFromString(string, "text/xml");
	} else {
		if (window.ActiveXObject) {
			/* var doc = new ActiveXObject("Microsoft.XMLDOM"); */
			var doc = new ActiveXObject("Msxml2.DOMDocument.3.0");
			doc.async = false;
			doc.validateOnParse = true;
			doc.loadXML(string);
		} else {
			doc = false;
		}
	}
	return doc;
}

function ty_xmltostring(sxml) {
	if (window.ActiveXObject) {
		if (sxml.xml) return sxml.xml;
	} else {
	return (new XMLSerializer()).serializeToString(sxml);
	}
}

/**
 * generic base64 function
 */
function ty_atob(value) {
    return(Base64.decode(value));
}

/* ------ DEPRECATED */
(function(){

var b64chars = 'ABCDEFGHIJKLMNOPQRSTUVWZYZabcdefghijklmnopqrstuvwzyz0123456789+/';

var b64tab = function(bin){
	var t = {};
	for (var i = 0, l = bin.length; i < l; i++) t[bin.charAt(i)] = i;
	return t;
}(b64chars);

var toBase64 = function(bin){
    if (bin.match(/[^\x00-\xFF]/)) throw 'unsupported character found' ;
	var padlen = 0;
	while(bin.length % 3) {
		bin += '\0';
		padlen++;
    };
	var b64 = '';
	for (var i = 0, l = bin.length; i < l; i += 3){
		var n = (bin.charCodeAt(i)  << 16)
				| (bin.charCodeAt(i+1) << 8)
				| (bin.charCodeAt(i+2));
		b64 += b64chars.charAt( n >>> 18)
			+ b64chars.charAt((n >>> 12) & 63)
			+ b64chars.charAt((n >>>  6) & 63)
			+ b64chars.charAt( n		 & 63);
	}
	if (!padlen) return b64;
	b64 = b64.substr(0, b64.length - padlen);
	while(padlen--) b64 += '=';
	return b64;
};

var btoa = window.btoa || toBase64;

var fromBase64 = function(b64){
	b64 = b64.replace(/[^A-Za-z0-9\+\/]/g, '');
	var bin = '';
	var padlen = 0;
	while(b64.length % 4){
		b64 += 'A';
		padlen++;
	}
	for (var i = 0, l = b64.length; i < l; i += 4){
		var n = (b64tab[b64.charAt(i  )] << 18)
				| (b64tab[b64.charAt(i+1)] << 12)
				| (b64tab[b64.charAt(i+2)] <<  6)
				| (b64tab[b64.charAt(i+3)]);
		bin += String.fromCharCode(  n >> 16 )
			+ String.fromCharCode( (n >>  8) & 0xff )
			+ String.fromCharCode(  n		 & 0xff );
	}
	bin.length -= [0,0,2,1][padlen];
	return bin;
};

var atob = window.atob || fromBase64;

var utob = function(uni){
	var bin = '';
	for (var i = 0, l = uni.length; i < l; i++){
		var n = uni.charCodeAt(i);
		bin += n < 0x80  ? uni.charAt(i)
			:  n < 0x800 ? String.fromCharCode(0xc0 | (n >>>  6))
						 + String.fromCharCode(0x80 | (n & 0x3f))
			:			   String.fromCharCode(0xe0 | ((n >>> 12) & 0x0f))
						 + String.fromCharCode(0x80 | ((n >>>  6) & 0x3f))
						 + String.fromCharCode(0x80 |  (n         & 0x3f))
			;
	}
	return bin;
};

var btou = function(bin){
	var uni = '';
	for (var i = 0, l = bin.length; i < l; i++){
		var c0 = bin.charCodeAt(i);
		if (c0 < 0x80){
			uni += bin.charAt(i)
		}else{
			var c1 = bin.charCodeAt(++i);
			if(c0 < 0xe0){
				uni += String.fromCharCode(((c0 & 0x1f) << 6) | (c1 & 0x3f));
			}else{
				var c2 = bin.charCodeAt(++i);
				uni += String.fromCharCode(
						((c0 & 0x0f) << 12) | ((c1 & 0x3f) <<  6) | (c2 & 0x3f)
						);
			}
		}
	}
	return uni;
}

try{
	eval('Base64')
}catch(e){
	Base64 = {
		fromBase64:fromBase64,
		toBase64:toBase64,
		atob:atob,
		btoa:btoa,
		utob:utob,
		btou:btou,
		encode:function(u){ return btoa(utob(u)) },
		encodeURI:function(u){
			return btoa(utob(u)).replace(/[+\/]/g, function(m0){
				return m0 == '+' ? '-' : '_';
			}).replace(/=+$/, '');
		},
		decode:function(a){
			return btou(atob(a.replace(/[-_]/g, function(m0){
				return m0 == '-' ? '+' : '/';
			})));
		}
	};
}

})();
/* ------ /DEPRECATED */



/**
 * search-/inputbox prediction
 */
var active_predict_field = null;
var active_predict_div = null;
var active_predict_elements = 0;
var active_predict_current = 0;
var active_predict_blur = false;
var active_predict = '';

function ty_prediction(srch_id,srch,val) {
	var predict = 'predict'+srch_id;
	active_predict=predict;

	if (!document.getElementById(predict)) return true;
	if (val==''){
		document.getElementById(predict).style.visibility='hidden';
		active_predict_field=null;
		active_predict_div=null;
	}else{
		var scriptElem = document.createElement('script');
		if (scriptElem) {
			scriptElem.setAttribute('src','/js/prediction__'+srch_id+'__'+srch+'__'+escape(val)+'.js');
			scriptElem.setAttribute('type','text/javascript');
			scriptElem.setAttribute('charset','utf-8');
			document.getElementsByTagName('head')[0].appendChild(scriptElem);
		}
	}
	return true;
}

function ty_predict_blur() {
	if (active_predict_blur==true){
		if (active_predict!=''){
			if (document.getElementById(active_predict)){
				document.getElementById(active_predict).style.visibility='hidden';
			}
		}
	}
}

function ty_predict_hi(divid,force) {
	if (!force) {
		if (active_predict_current==divid) return true;
	}
	if (document.getElementById('predict_content_'+divid)) {
		if (document.getElementById('predict_content_'+active_predict_current)) {
			document.getElementById('predict_content_'+active_predict_current).className='ty_predictline_off';
		}
		document.getElementById('predict_content_'+divid).className='ty_predictline_on';
		active_predict_current=divid;
	}
	return true;
}

function ty_keyup(evt) {
	/* 37 left, 39 right */
	var t=true;
	evt=(evt)?evt:((window.event)?event:null);
	if ( (active_predict_field==null) || (active_predict_div==null) || (active_predict_elements==0) ) evt=null;
	if (evt) {
		switch (evt.keyCode) {
			case 13:
				/* enter */
				t=false;
				if (active_predict_current>=1) {
					document.getElementById('predict_cbutton_'+active_predict_current).click();
					active_predict_current=0;
				}
				break;
			case 38:
				/* up */
				t=false;
				if (active_predict_current==1) {
					document.getElementById('predict_content_'+active_predict_current).className='ty_predictline_off';
					active_predict_blur=true;
					document.getElementById(active_predict_div).blur();
					document.getElementById(active_predict_field).focus();
					active_predict_current--;
				}else{
					if (active_predict_current>1) {
						document.getElementById('predict_content_'+active_predict_current).className='ty_predictline_off';
						active_predict_current--;
						document.getElementById('predict_content_'+active_predict_current).className='ty_predictline_on';
					}
				}
				break;
			case 40:
				/* down */
				t=false;
				if (active_predict_current==0) {
					document.getElementById(active_predict_field).blur();
					document.getElementById(active_predict_div).focus();
					active_predict_current++;
					document.getElementById('predict_content_'+active_predict_current).className='ty_predictline_on';
				}else{
					if ( (active_predict_current>=1) && (active_predict_current < active_predict_elements) ) {
						document.getElementById('predict_content_'+active_predict_current).className='ty_predictline_off';
						active_predict_current++;
						document.getElementById('predict_content_'+active_predict_current).className='ty_predictline_on';
					}
				}
			break;
		}
	}
    return(t);
}

document.onkeyup = ty_keyup;

/**
 * select formelements
 */
var active_formelementitem = 0;
var allow_change_formelementitem = 0;
var slf='';

function ty_selectformelementitems(divid,force) {
	if (!force) {
		if (active_formelementitem==divid) return true;
		if (allow_change_formelementitem>0) return true;
	}
	if (document.getElementById('selecttd'+divid)) {
		if (document.getElementById('selecttd'+active_formelementitem)) {
			document.getElementById('selecttd'+active_formelementitem).innerHTML='';
		}
		document.getElementById('selecttd'+divid).innerHTML=ty_atob(slf);
		active_formelementitem=divid;
	}
	return true;
}

/**
 * get mouse position as ty_mouse(X|Y)
 */

var ty_mouseX = 0;
var ty_mouseY = 0;

function ty_get_mouseXY(e) {
	if (document.all) {
		ty_mouseX = event.clientX + document.body.scrollLeft;
		ty_mouseY = event.clientY + document.body.scrollTop;
	} else {
		ty_mouseX = e.pageX;
		ty_mouseY = e.pageY;
	}
	if (ty_mouseX < 0) ty_mouseX = 0;
	if (ty_mouseY < 0) ty_mouseY = 0;
	return(true);
}

if (!document.all) document.captureEvents(Event.MOUSEMOVE);
document.onmousemove = ty_get_mouseXY;

/**
 * crossbrowser event registry
 */
function ty_addEvent(obj, evtype, fn) {
	if (obj.addEventListener) {
		obj.addEventListener(evtype, fn, false); /* no use of Caption here */
		return(true);
	} else if (obj.attachEvent) {
		var retVal = obj.attachEvent("on"+evtype, fn);
		return(retVal);
	} else {
		return(false);
	}
}

function findArea(obj) {
	var curleft = curtop = curwidth = curheight = 0;
	if (obj.style.pixelWidth) {
		curwidth = obj.style.pixelWidth;
	} else {
		if (obj.offsetWidth) {
			curwidth = obj.offsetWidth;
		}
	}
	if (obj.style.pixelHeight) {
		curheight = obj.style.pixelHeight;
	}
	else {
		if (obj.offsetHeight) {
			curheight = obj.offsetHeight;
		}
	}
	if (obj.offsetParent) {
		curleft = obj.offsetLeft;
		curtop = obj.offsetTop;
		while (obj = obj.offsetParent) {
			curleft += obj.offsetLeft;
			curtop += obj.offsetTop
		}
	}
	return [curleft,curtop,curwidth,curheight];
}

function ty_fader(fadeObjectId, opacity, sens, duration) {
	opacity = (opacity == 100)? 99.999 : opacity;
	document.getElementById(fadeObjectId).style.filter = "alpha(opacity:"+opacity+")";
	document.getElementById(fadeObjectId).style.KHTMLOpacity = opacity/100;
	document.getElementById(fadeObjectId).style.MozOpacity = opacity/100;
	document.getElementById(fadeObjectId).style.opacity = opacity/100
	if(sens>0 && opacity<99 || sens<0 && opacity>0) {
		opacity += 1*sens;
		setTimeout(
			function(){ty_fader(fadeObjectId, opacity, sens, duration);}
			,duration);
	}
}

function ty_hideElementId(hideObjectId) {
	//ty_fader(hideObjectId,1,10,1);
	document.getElementById(showObjectId).style.visibility="hidden";
}

function ty_showElementId(showObjectId) {
	//ty_fader(showObjectId,98,-10,1);
	document.getElementById(showObjectId).style.visibility="visible";
}


/************** UTF8 q&d ******************/
/* UTF8 encoding/decoding functions
 * Copyright (c) 2006 by Ali Farhadi.
 * released under the terms of the Gnu Public License.
 * see the GPL for details.
 *
 * Email: ali[at]farhadi[dot]ir
 * Website: http://farhadi.ir/
 */

//an alias of String.fromCharCode
function _ty_chr(code) {
	return String.fromCharCode(code);
}

//returns utf8 encoded charachter of a unicode value.
//code must be a number indicating the Unicode value.
//returned value is a string between 1 and 4 charachters.
function ty_code2utf(code) {
	if (code < 128) return _ty_chr(code);
	if (code < 2048) return _ty_chr(192+(code>>6)) + _ty_chr(128+(code&63));
	if (code < 65536) return _ty_chr(224+(code>>12)) + _ty_chr(128+((code>>6)&63)) + _ty_chr(128+(code&63));
	if (code < 2097152) return _ty_chr(240+(code>>18)) + _ty_chr(128+((code>>12)&63)) + _ty_chr(128+((code>>6)&63)) + _ty_chr(128+(code&63));
}

//it is a private function for internal use in utf8Encode function
function _ty_utf8Encode(str) {
	var utf8str = new Array();
	for (var i=0; i < str.length; i++) {
		utf8str[i] = ty_code2utf(str.charCodeAt(i));
	}
	return utf8str.join('');
}

/* Encodes a unicode string to UTF8 format. */
function ty_utf8Encode(str) {
	var utf8str = new Array();
	var pos,j = 0;
	var tmpStr = '';
	
	while ((pos = str.search(/[^\x00-\x7F]/)) != -1) {
		tmpStr = str.match(/([^\x00-\x7F]+[\x00-\x7F]{0,10})+/)[0];
		utf8str[j++] = str.substr(0, pos);
		utf8str[j++] = _ty_utf8Encode(tmpStr);
		str = str.substr(pos + tmpStr.length);
	}
	
	utf8str[j++] = str;
	return utf8str.join('');
}

//it is a private function for internal use in utf8Decode function
function _ty_utf8Decode(utf8str) {
	var str = new Array();
	var code,code2,code3,code4,j = 0;
	for (var i=0; i < utf8str.length; ) {
		code = utf8str.charCodeAt(i++);
		if (code > 127) code2 = utf8str.charCodeAt(i++);
		if (code > 223) code3 = utf8str.charCodeAt(i++);
		if (code > 239) code4 = utf8str.charCodeAt(i++);
		
		if (code < 128) str[j++]= _ty_chr(code);
		else if (code < 224) str[j++] = _ty_chr(((code-192)<<6) + (code2-128));
		else if (code < 240) str[j++] = _ty_chr(((code-224)<<12) + ((code2-128)<<6) + (code3-128));
		else str[j++] = _ty_chr(((code-240)<<18) + ((code2-128)<<12) + ((code3-128)<<6) + (code4-128));
	}
	return str.join('');
}

//Decodes a UTF8 formated string
function ty_utf8Decode(utf8str) {
	var str = new Array();
	var pos = 0;
	var tmpStr = '';
	var j=0;
	while ((pos = utf8str.search(/[^\x00-\x7F]/)) != -1) {
		tmpStr = utf8str.match(/([^\x00-\x7F]+[\x00-\x7F]{0,10})+/)[0];
		str[j++]= utf8str.substr(0, pos) + _ty_utf8Decode(tmpStr);
		utf8str = utf8str.substr(pos + tmpStr.length);
	}
	
	str[j++] = utf8str;
	return str.join('');
}

/************ BASE64 new q&d *******************/
/* Base64 conversion methods.
 * Copyright (c) 2006 by Ali Farhadi.
 * released under the terms of the Gnu Public License.
 * see the GPL for details.
 *
 * Email: ali[at]farhadi[dot]ir
 * Website: http://farhadi.ir/
 */

//Encodes data to Base64 format
function ty_base64Encode(data) {
	if (typeof(btoa) == 'function') return btoa(data);//use internal base64 functions if available (gecko only)
	var b64_map = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
	var byte1, byte2, byte3;
	var ch1, ch2, ch3, ch4;
	var result = new Array(); //array is used instead of string because in most of browsers working with large arrays is faster than working with large strings
	var j=0;
	for (var i=0; i < data.length; i+=3) {
		byte1 = data.charCodeAt(i);
		byte2 = data.charCodeAt(i+1);
		byte3 = data.charCodeAt(i+2);
		ch1 = byte1 >> 2;
		ch2 = ((byte1 & 3) << 4) | (byte2 >> 4);
		ch3 = ((byte2 & 15) << 2) | (byte3 >> 6);
		ch4 = byte3 & 63;
		
		if (isNaN(byte2)) {
			ch3 = ch4 = 64;
		} else if (isNaN(byte3)) {
			ch4 = 64;
		}

		result[j++] = b64_map.charAt(ch1)+b64_map.charAt(ch2)+b64_map.charAt(ch3)+b64_map.charAt(ch4);
	}

	return result.join('');
}

//Decodes Base64 formated data
function ty_base64Decode(data) {
	data = data.replace(/[^a-z0-9\+\/=]/ig, '');// strip none base64 characters
	if (typeof(atob) == 'function') return atob(data);//use internal base64 functions if available (gecko only)
	var b64_map = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
	var byte1, byte2, byte3;
	var ch1, ch2, ch3, ch4;
	var result = new Array(); //array is used instead of string because in most of browsers working with large arrays is faster than working with large strings
	var j=0;
	while ((data.length%4) != 0) {
		data += '=';
	}
	
	for (var i=0; i < data.length; i+=4) {
		ch1 = b64_map.indexOf(data.charAt(i));
		ch2 = b64_map.indexOf(data.charAt(i+1));
		ch3 = b64_map.indexOf(data.charAt(i+2));
		ch4 = b64_map.indexOf(data.charAt(i+3));

		byte1 = (ch1 << 2) | (ch2 >> 4);
		byte2 = ((ch2 & 15) << 4) | (ch3 >> 2);
		byte3 = ((ch3 & 3) << 6) | ch4;

		result[j++] = String.fromCharCode(byte1);
		if (ch3 != 64) result[j++] = String.fromCharCode(byte2);
		if (ch4 != 64) result[j++] = String.fromCharCode(byte3);
	}

	return result.join('');
}


function ty_setcookie( name, value, expires, path, domain, secure ) {
    var today = new Date();
    today.setTime( today.getTime() );

    if ( expires ) {
	expires = expires * 1000 * 60 * 60 * 24;
    }
    var expires_date = new Date( today.getTime() + (expires) );

    document.cookie = name + "=" +escape( value ) +
	( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) +
	( ( path ) ? ";path=" + path : "" ) +
	( ( domain ) ? ";domain=" + domain : "" ) +
	( ( secure ) ? ";secure" : "" );
}

function ty_getcookie( check_name ) {
    var a_all_cookies = document.cookie.split( ';' );
    var a_temp_cookie = '';
    var cookie_name = '';
    var cookie_value = '';
    var b_cookie_found = false; // set boolean t/f default f
    for ( i = 0; i < a_all_cookies.length; i++ ) {
	a_temp_cookie = a_all_cookies[i].split( '=' );
	cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');
	if ( cookie_name == check_name ) {
	    b_cookie_found = true;
	    if ( a_temp_cookie.length > 1 ) {
		cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') );
	    }
	    return cookie_value;
	    break;
	}
	a_temp_cookie = null;
	cookie_name = '';
    }
    if ( !b_cookie_found ) {
	return null;
    }
}

function ty_rollator_getposition( pagename ) {
	var y;
	y=0;
	if (document.body && document.body.scrollTop) {
 		y=document.body.scrollTop;
	} else {
 		if (document.documentElement && document.documentElement.scrollTop) {
			y=document.documentElement.scrollTop;
 		} else {
			if (window.pageYOffset) {
				y=window.pageYOffset;
			}
		}
	}
 ty_setcookie("ty_rollator"+pagename,y);
}

