/* SVN FILE: $Id: EPSTicketing.js 2528 2010-05-02 17:43:00Z theo $ */
/**
 * Project Name : EPSVenue
 *
 * @author $Author: theo $
 * @version $Revision: 2528 $
 * @lastrevision $Date: 2010-05-02 19:43:00 +0200 (Sun, 02 May 2010) $
 * @modifiedby $LastChangedBy: theo $
 * @lastmodified $LastChangedDate: 2010-05-02 19:43:00 +0200 (Sun, 02 May 2010) $
 */
/*global getURL toggle clearUnsetVariables */
var oldSelectedLine;
/**
*
*/
function $(id) {
	return document.getElementById(id);
}
/**
*
*/
function viewLine(id, url, target) {
	if ($(id) && id !== null) {
		$(id).className = 'highlight';
	}
	if (undefined !== oldSelectedLine && oldSelectedLine !== id) {
		$(oldSelectedLine).className = 'noHighlight';
	}
	oldSelectedLine = id; // urls can't user ampersand entities, so replace them with plane ampersands
	url = url.replace(/&amp;/g, '&');
	getURL(url, target, {});
}
/**
*
*/
function rgbConvert(str) {
	str = str.replace(/rgb\(|\)/g, "").split(",");
	str[0] = parseInt(str[0], 10).toString(16).toLowerCase();
	str[1] = parseInt(str[1], 10).toString(16).toLowerCase();
	str[2] = parseInt(str[2], 10).toString(16).toLowerCase();
	str[0] = (str[0].length === 1) ? '0' + str[0] : str[0];
	str[1] = (str[1].length === 1) ? '0' + str[1] : str[1];
	str[2] = (str[2].length === 1) ? '0' + str[2] : str[2];
	return ('#' + str.join(""));
}
var baseColor = '#ffffff';
var overColor = '#cccccc';
var selectedColor = '#cfe6cf';
var lineSelected = '';
/**
*
*/
function lineOver(el) {
	if (rgbConvert(el.style.backgroundColor) !== selectedColor && el.style.backgroundColor !== selectedColor) {
		el.style.backgroundColor = overColor;
		el.style.cursor = 'pointer';
	}
}
/**
*
*/
function lineOut(el) {
	if (rgbConvert(el.style.backgroundColor) === overColor || el.style.backgroundColor === overColor) {
		el.style.backgroundColor = baseColor;
		el.style.cursor = 'default';
	}
}
/**
*
*/
function lineClick(el, id, url) {
	if (lineSelected !== '') {
		lineSelected.style.backgroundColor = baseColor;
	}
	el.style.backgroundColor = selectedColor;
	if (url !== '') {
		viewLine(id, url, 'detail');
	}
	lineSelected = el;
}
/**
*
*/
var selectedTab = '';
function doTab(id, action, url) {
	if (action === 'on' && id !== selectedTab) {
		$('tab' + id).style.background = '#def';
	} else if (action === 'off' && id !== selectedTab) {
		$('tab' + id).style.background = '#fff';
	} else if (action === 'selected') {
		selectedTab = id;
		for (var i = 0; i < 7; i++) {
			doTab(i, 'off');
		}
		$('tab' + id).style.background = '#ccc';
		if (url !== '') {
			if (id === 0) {
				$('performancesID').style.display = 'block';
			}
			getURL(url, 'content', {});
		}
	}
}
/**
*
*/
function switchAuditImg(divId, imgId) {
	try {
		toggle(divId);
		if ($(divId).style.display === 'block') {
			$(imgId).src = '/EPSVenue/images/cms/pointer_d.png';
		} else {
			$(imgId).src = '/EPSVenue/images/cms/pointer_r.png';
		}
	} finally {}
}
/**
*
*/
function switchLine(current) {
	if (current === 'tdprompt') {
		current = 'tdprompt_alt1';
	} else {
		current = 'tdprompt';
	}
	return current;
}
/**
*
*/
function moveSelectedElements(leftId, rightId, direction) {
	var from;
	var dest;
	if (direction === 'ltr') {
		from = leftId;
		dest = rightId;
	} else {
		from = rightId;
		dest = leftId;
	} // move selected elements to other box
	for (var i = 0; i < $(from).childNodes.length; i++) {
		if ($(from).childNodes[i].value !== undefined) {
			if ($(from).childNodes[i].selected) {
				var elVar = $(from).childNodes[i].value;
				var elTxt = $(from).childNodes[i].text;
				if (elVar !== undefined && elVar !== 0) { // only move elements that have a value other than zero
					var elementsInTarget = 0; // count everytime because tidy adds empty text elements
					for (var j = 0; j < $(dest).childNodes.length; j++) {
						if ($(dest).childNodes[j].value !== undefined) {
							elementsInTarget++;
						}
					}
					$(dest).options[elementsInTarget] = new Option(elTxt, elVar);
				}
			}
		}
	} // remove selected elements from original box
	/// count select elements
	var l = $(from).childNodes.length - 1;
	var selectElementsCount = 0;
	for (i = l; i >= 0; i--) {
		if ($(from).childNodes[i].value !== undefined) {
			selectElementsCount++;
		}
	}
	j = 0;
	for (i = l; i >= 0; i--) {
		if ($(from).childNodes[i].value !== undefined) {
			j++;
		}
		if ($(from).childNodes[i].selected) {
			$(from).options[selectElementsCount - j] = null;
		}
	}
}
/**
*
*/
function moveAndSaveSelectedElements(leftId, rightId, direction, url) {
	moveSelectedElements(leftId, rightId, direction);
	saveSelectedItems(rightId, url);
}
/**
*
*/
function activateSelectedElements(selector) {
	for (var i = 0; i < $(selector).childNodes.length; i++) {
		$(selector).childNodes[i].selected = true;
	}
	document.shopsSelector.submit();
}
/**
*
*/
function saveSelectedItems(selectedBoxId, target) {
	var l = $(selectedBoxId).childNodes.length;
	var list ='';
	for (var i = 0; i < l; i++) {
		var elVar = $(selectedBoxId).childNodes[i].value;
		list += elVar + ',';
	}
	if(target.indexOf('/',0)>=0) {
		// assumed url, if it contains a / (slash)
		var url = target + '&selectedElements=' + list;
		getURL(url, '', {});
	} else {
		//  target id Id of HTML Input element
		$(target).value=list;
	}
	

}
/**
*
*/
function submitForm(formId, elId) {
	try {
		clearUnsetVariables($(formId));
		if (elId !== undefined && elId !== '') {
			var selectedBoxId = 'selectedItems';
			if ($(selectedBoxId)) {
				var l = $(selectedBoxId).childNodes.length;
				if (l > 0) {
					var list = '';
					for (var i = 0; i < l; i++) {
						var elVar = $(selectedBoxId).childNodes[i].value;
						list += elVar + ',';
					}
					$(elId).value = list;
				}
			}
		}
		$(formId).submit();
	} catch (e) {
		var msg = '\n';
		if (formId === undefined) {
			msg += 'Er moet een formId opgegeven worden van het formulier.\n';
		}
		if (elId === undefined) {
			msg += 'Er moet een elId opgegeven worden wat de lijst van geselecteerde items doorgeeft.\n';
		}
		alert(e + msg);
	}
}
/**
*
*/
function clearUnsetVariables(el) {
	if (el !== null) { // el must exist
		for (var i = 0; i < el.childNodes.length; i++) {
			if (el.childNodes[i].className && el.childNodes[i].className.indexOf('_dimmed') > 0) {
				el.childNodes[i].value = '';
			}
			clearUnsetVariables(el.childNodes[i]);
		}
	}
}
/**
*
*/
function searchSuggest(url, el, e, suggestContainer, database_column) {
	try {
		var elID = el.id;
		var q = $(elID).value;
		var target = elID + 'suggest';
		var charCode = (e.which) ? e.which: event.keyCode;
		var hasParam = url.indexOf('?');
		var concatenator;
		if (hasParam === 0) {
			concatenator = '?';
		} else {
			concatenator = '&';
		}
		if (charCode === 13) // return
		{
			url = document.location.href.split('?')[0]; //document.location.href.split('?')[0];
			url += '?a=getRecords&column=' + database_column + '&q=' + q;
			document.location.href = url;
			return;
		} else if (charCode === 27) {
			$(suggestContainer).value = '';
			$(suggestContainer + 'suggest').innerHTML = '';
			return;
		} else {
			url += concatenator + 'q=' + q;
		}
		getURL(url, target, {
			hideWaitIcon: true
		});
	} finally {}
}
/**
*
*/
function masterSearch(url, id, el) {
	try {
		var q = $('i' + id).value;
		var charCode = (el.which) ? el.which: event.keyCode;
		var hasParam = url.indexOf('?');
		var concatenator;
		if (hasParam === 0) {
			concatenator = '?';
		} else {
			concatenator = '&';
		}
		if (charCode === 13) // return
		{
			url += concatenator + 'q=' + q;
			document.location.href = url;
			return;
		} else if (charCode === 27) {
			$('i' + id).value = '';
			return;
		} else {}
	} catch (e) {
		alert(e);
	} finally {}
}
/**
*
*/
// highlight searchbox and clear initial content
function masterSearchFocus(id) {
	if ($(id).className === 'input_0_dimmed') {
		$(id).className = 'input_0';
		$(id).value = '';
	}
}
/**
*
*/
function toggle(el) {
	var imgelID = $('img' + el);
	if ($(el).style.display === 'none') {
		if (imgelID !== null) {
			imgelID.src = '/eps/images/cms/pointer_d.png';
		}
		$(el).style.display = 'block';
	} else {
		if (imgelID !== null) {
			imgelID.src = '/eps/images/cms/pointer_r.png';
		}
		$(el).style.display = 'none';
	}
}
/**
*
*/
function highLightTab(id, count) {
	try {
		var shiftA = 0; // is needed in case of HTML Tidy which adds empty text nodes
		var shiftM = 1; // is needed in case of HTML Tidy which adds empty text nodes	
		if ($('detailedTab' + 0).childNodes[0].style === undefined) { // is needed in case of HTML Tidy which adds empty text nodes (eval weggehaald volgens JSLINT is eval=evil!!!)
			shiftA = 1;
			shiftM = 2;
		}
		for (var i = 0; i <= count - 1; i++) { // hide item
			$('detailedItem' + i).style.display = 'none'; // reset tab
			$('detailedTab' + i).childNodes[0 * shiftM + shiftA].style.backgroundImage = 'url(/EPSVenue/images/cms/tab_left.gif)'; // 0
			$('detailedTab' + i).childNodes[1 * shiftM + shiftA].style.backgroundImage = 'url(/EPSVenue/images/cms/tab.gif)'; // 1
			$('detailedTab' + i).childNodes[2 * shiftM + shiftA].style.backgroundImage = 'url(/EPSVenue/images/cms/tab_right.gif)'; // 2
			$('detailedTab' + i).childNodes[1 * shiftM + shiftA].className = 'tabTxt'; // 1			
		}
		$('detailedItem' + id).style.display = 'block'; // highlight tab
		$('detailedTab' + id).childNodes[0 * shiftM + shiftA].style.backgroundImage = "url(/EPSVenue/images/cms/tab_left_h.gif)";
		$('detailedTab' + id).childNodes[1 * shiftM + shiftA].style.backgroundImage = 'url(/EPSVenue/images/cms/tab_h.gif)';
		$('detailedTab' + id).childNodes[2 * shiftM + shiftA].style.backgroundImage = 'url(/EPSVenue/images/cms/tab_right_h.gif)';
		$('detailedTab' + id).childNodes[1 * shiftM + shiftA].className = 'tabTxt_h';
	} catch (e) {
		alert('Regel: 357 \n' + e);
	}
}
/**
*
*/
function convertStr2Date(str) {
	try {
		if (str !== '' && str.indexOf(' ', 0) > 0 && str.indexOf('-', 0) > 0 && str.indexOf(':', 0) > 0) {
			var date_time = str.split(' ');
			var dateAr = date_time[0].split('-');
			var timeAr = date_time[1].split(':');
			var year = 0 + parseInt(dateAr[0], 10);
			var month;
			var day;
			var hour;
			var min;
			var sec;
			if (isNaN(year)) {
				hour = 2007;
			}
			month = 0 + parseInt(dateAr[1], 10) - 1;
			if (isNaN(month)) {
				min = 0;
			}
			day = 0 + parseInt(dateAr[2], 10);
			if (isNaN(day)) {
				sec = 1;
			}
			hour = 0 + parseInt(timeAr[0], 10);
			if (isNaN(hour)) {
				hour = 0;
			}
			min = 0 + parseInt(timeAr[1], 10);
			if (isNaN(min)) {
				min = 0;
			}
			sec = 0 + parseInt(timeAr[2], 10);
			if (isNaN(sec)) {
				sec = 0;
			}
			date_time = new Date(year, month, day, hour, min, sec);
			return date_time;
		}
	} catch (e) {
		alert('ERROR: @".__LINE__.": ' + str + '\\n' + e);
	}
}
/**
*
*/
function number_format(number, decimals, dec_point, thousands_sep) {
    // http://kevin.vanzonneveld.net
    // +   original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +     bugfix by: Michael White (http://getsprink.com)
    // +     bugfix by: Benjamin Lupton
    // +     bugfix by: Allan Jensen (http://www.winternet.no)
    // +    revised by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
    // +     bugfix by: Howard Yeend
    // *     example 1: number_format(1234.5678, 2, '.', '');
    // *     returns 1: 1234.57     
 
    var n = number, c = isNaN(decimals = Math.abs(decimals)) ? 2 : decimals;
    var d = dec_point === undefined ? "." : dec_point;
    var t = thousands_sep === undefined ? "," : thousands_sep, s = n < 0 ? "-" : "";
    var i = parseInt(n = Math.abs(+n || 0).toFixed(c), 10) + "", j = (j = i.length) > 3 ? j % 3 : 0;
    
    return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : "");
}
/**
*
*/
Array.prototype.in_array = function (element) {
	var retur = false;
	for (var values in this) {
		if (this[values] === element) {
			retur = true;
			break;
		}
	}
	return retur;
};
function isValueSet(id) {
	if($(id) !== null && $(id).value !== undefined && $(id).value!=='') {
		return true;
	} else {
		return false;
	}
}
/**
 *
 */
function checkForm(checkStr, form) {
	var msg='';
	var fieldsAr=checkStr.split('|');
	for(var i = 0; i < fieldsAr.length; i++) {
		var pair=fieldsAr[i].split('#');
		var id=pair[0];
		var label=pair[1];
		if(!isValueSet(id)) {
			msg+='- ' + label + '.\n';
		}
	}
	if(msg!=='') {
		alert('De volgende velden zijn verplicht:\n' + msg);
	} else {
		$(form).submit();
	}
	
	
} 
/**
 *
 */
function parseJSON(json) {
	try {
		if(/^("(\\.|[^"\\\n\r])*?"|[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t])+?$/.test(json)){
		var j = eval('(' + json + ')');
		return j;
		}
	}catch(e){
	//	alert(e + '\n@' + e.lineNmber + '\n' + json);
	}
	throw new SyntaxError("parseJSON");
}
/**
 *
 */
function array_push ( array ) {
    // Pushes elements onto the end of the array  
    // 
    // version: 810.114
    // discuss at: http://phpjs.org/functions/array_push
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // *     example 1: array_push(['kevin','van'], 'zonneveld');
    // *     returns 1: 3
    var i, argv = arguments, argc = argv.length;

    for (i=1; i < argc; i++){
        array[array.length++] = argv[i];
    }

    return array.length;
}
/**
 *
 */
function array_diff() {
    // Returns the entries of arr1 that have values which are not present in any of the others arguments.  
    // 
    // version: 901.1301
    // discuss at: http://phpjs.org/functions/array_diff
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Sanjoy Roy
    // +    revised by: Brett Zamir
    // *     example 1: array_diff(['Kevin', 'van', 'Zonneveld'], ['van', 'Zonneveld']);
    // *     returns 1: ['Kevin']
    var arr1 = arguments[0], retArr = {};
    var k1 = '', i = 1, k = '', arr = {};

    arr1keys:
    for (k1 in arr1) {
        for (i = 1; i < arguments.length; i++) {
            arr = arguments[i];
            for (k in arr) {
                if (arr[k] === arr1[k1]) {
                    // If it reaches here, it was found in at least one array, so try next value
                    continue arr1keys; 
                }
            }
            retArr[k1] = arr1[k1];
        }
    }

    return retArr;
}
/** 
 *  Remove arrayElement from arrayName
 */
function removeByElement(arrayName,arrayElement)
 {
    for(var i=0; i<arrayName.length;i++ )
     { 
        if(arrayName[i]==arrayElement)
            arrayName.splice(i,1); 
      } 
  }
/** parentNode.childNodes[i]
 *  Remove element from DOM
 */  
function removeElement(ElId) {
	try {
		if($(ElId).parentNode !==null && $(ElId).parentNode!==undefined){
			var parentNode=$(ElId).parentNode;
			var i=0;
			var removed=false;
			while(i<parentNode.childNodes.length ) {
				i++;
				if(typeof parentNode.childNodes[i]!=='undefined' && parentNode.childNodes[i].id == ElId) {
					parentNode.removeChild($(ElId).parentNode.childNodes[i]);
					removed=true;
				}
			}
		}
	} catch(err) {
		alert('removeElement: ' + err);
	}
}
/** 
 *  
 */  
function formatAccountnr(el) {
	try {
		var account=el.value;
		if (account=='') {
			return;			
		}
		account=account.replace(/\D/g, '');
		account=parseFloat(account);
		if(isNaN(account)) {
			account=0;
		}
		var accountStr=account+'';
		var l=accountStr.length;
		var prefix='';
		var i;
		for(i=9-l; i>0; i--) {
			prefix += '0';
		}
		if(prefix!='' && accountStr.length<9) {
			el.value='P' + prefix + account;
		} else {
			for(i=10-l; i>0; i--) {
				prefix+='0';
			}
			el.value=prefix + account;
		}
	} catch(err) {
		alert(err);
	}
}
/*
 *
 */
function findPos(obj) {
	var curleft = curtop = 0;
	if (obj.offsetParent) {
		curleft = obj.offsetLeft
		curtop = obj.offsetTop
		while (obj = obj.offsetParent) {
			curleft += obj.offsetLeft
			curtop += obj.offsetTop
		}
	}
	return [curleft,curtop];
}
// -------------------------------------------------------------------
function BRErrorHandler(http) {
	var resObj=parseJSON(http.responseText);
	//alert(http.responseText);
	var Code=resObj.EPSVenue.Result.Code;
	var Message=resObj.EPSVenue.Result.Message;

	
	if(Code!=0) {
		alert(Message);
		return false;
	}
	return true;
}

function setcookie(name, value, expires, path, domain, secure) {
    // Send a cookie 
    //
    // version: 905.412
    // discuss at: http://phpjs.org/functions/setcookie
    // +   original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
    // +   bugfixed by: Andreas
    // +   bugfixed by: Onno Marsman
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // -    depends on: setrawcookie
    // *     example 1: setcookie('author_name', 'Kevin van Zonneveld');
    // *     returns 1: true
    return this.setrawcookie(name, encodeURIComponent(value), expires, path, domain, secure);
}


function setrawcookie(name, value, expires, path, domain, secure) {                       
    // Send a cookie with no url encoding of the value                                 
    //                                                                                 
    // version: 905.2214                                                               
    // discuss at: http://phpjs.org/functions/setrawcookie                             
    // +   original by: Brett Zamir (http://brettz9.blogspot.com)                      
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)            
    // +   derived from: setcookie                                                     
    // *     example 1: setcookie('author_name', 'Kevin van Zonneveld');               
    // *     returns 1: true                                                           
    if (expires instanceof Date) {                                                     
        expires = expires.toGMTString();                                               
    } else if(typeof(expires) == 'number') {                                           
        expires = (new Date(+(new Date()) + expires * 1e3)).toGMTString();             
    }                                                                                  
                                                                                       
    var r = [name + "=" + value], s={}, i='';                                          
    s = {expires: expires, path: path, domain: domain};                                
    for(i in s){                                                                       
        s[i] && r.push(i + "=" + s[i]);                                                
    }                                                                                  
                                                                                       
    return secure && r.push("secure"), this.window.document.cookie = r.join(";"), true;
}                                                                                      
function urlencode (str) {
    // URL-encodes string  
    // 
    // version: 910.813
    // discuss at: http://phpjs.org/functions/urlencode
    // +   original by: Philip Peterson
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: AJ
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Brett Zamir (http://brett-zamir.me)
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: travc
    // +      input by: Brett Zamir (http://brett-zamir.me)
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Lars Fischer
    // +      input by: Ratheous
    // +      reimplemented by: Brett Zamir (http://brett-zamir.me)
    // +   bugfixed by: Joris
    // %          note 1: This reflects PHP 5.3/6.0+ behavior
    // *     example 1: urlencode('Kevin van Zonneveld!');
    // *     returns 1: 'Kevin+van+Zonneveld%21'
    // *     example 2: urlencode('http://kevin.vanzonneveld.net/');
    // *     returns 2: 'http%3A%2F%2Fkevin.vanzonneveld.net%2F'
    // *     example 3: urlencode('http://www.google.nl/search?q=php.js&ie=utf-8&oe=utf-8&aq=t&rls=com.ubuntu:en-US:unofficial&client=firefox-a');
    // *     returns 3: 'http%3A%2F%2Fwww.google.nl%2Fsearch%3Fq%3Dphp.js%26ie%3Dutf-8%26oe%3Dutf-8%26aq%3Dt%26rls%3Dcom.ubuntu%3Aen-US%3Aunofficial%26client%3Dfirefox-a'
    var hexStr = function (dec) {
        return '%' + (dec < 16 ? '0' : '') + dec.toString(16).toUpperCase();
    };

    var ret = '',
            unreserved = /[\w.-]/; // A-Za-z0-9_.- // Tilde is not here for historical reasons; to preserve it, use rawurlencode instead
    str = (str+'').toString();

    for (var i = 0, dl = str.length; i < dl; i++) {
        var ch = str.charAt(i);
        if (unreserved.test(ch)) {
            ret += ch;
        }
        else {
            var code = str.charCodeAt(i);
            if (0xD800 <= code && code <= 0xDBFF) { // High surrogate (could change last hex to 0xDB7F to treat high private surrogates as single characters); https://developer.mozilla.org/index.php?title=en/Core_JavaScript_1.5_Reference/Global_Objects/String/charCodeAt
                ret += ((code - 0xD800) * 0x400) + (str.charCodeAt(i+1) - 0xDC00) + 0x10000;
                i++; // skip the next one as we just retrieved it as a low surrogate
            }
            // We never come across a low surrogate because we skip them, unless invalid
            // Reserved assumed to be in UTF-8, as in PHP
            else if (code === 32) {
                ret += '+'; // %20 in rawurlencode
            }
            else if (code < 128) { // 1 byte
                ret += hexStr(code);
            }
            else if (code >= 128 && code < 2048) { // 2 bytes
                ret += hexStr((code >> 6) | 0xC0);
                ret += hexStr((code & 0x3F) | 0x80);
            }
            else if (code >= 2048) { // 3 bytes (code < 65536)
                ret += hexStr((code >> 12) | 0xE0);
                ret += hexStr(((code >> 6) & 0x3F) | 0x80);
                ret += hexStr((code & 0x3F) | 0x80);
            }
        }
    }
    return ret;
}

function urldecode( str ) {
    // Decodes URL-encoded string 
    //
    // version: 905.3122
    // discuss at: http://phpjs.org/functions/urldecode
    // +   original by: Philip Peterson
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: AJ
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Brett Zamir (http://brett-zamir.me)
    // +      input by: travc
    // +      input by: Brett Zamir (http://brett-zamir.me)
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Lars Fischer
    // %          note 1: info on what encoding functions to use from: http://xkr.us/articles/javascript/encode-compare/
    // *     example 1: urldecode('Kevin+van+Zonneveld%21');
    // *     returns 1: 'Kevin van Zonneveld!'
    // *     example 2: urldecode('http%3A%2F%2Fkevin.vanzonneveld.net%2F');
    // *     returns 2: 'http://kevin.vanzonneveld.net/'
    // *     example 3: urldecode('http%3A%2F%2Fwww.google.nl%2Fsearch%3Fq%3Dphp.js%26ie%3Dutf-8%26oe%3Dutf-8%26aq%3Dt%26rls%3Dcom.ubuntu%3Aen-US%3Aunofficial%26client%3Dfirefox-a');
    // *     returns 3: 'http://www.google.nl/search?q=php.js&;ie=utf-8&oe=utf-8&aq=t&rls=com.ubuntu:en-US:unofficial&client=firefox-a'
     
    var histogram = {}, ret = str.toString(), unicodeStr='', hexEscStr='';
     
    var replacer = function(search, replace, str) {
        var tmp_arr = [];
        tmp_arr = str.split(search);
        return tmp_arr.join(replace);
    };
     
    // The histogram is identical to the one in urlencode.
    histogram["'"]   = '%27';
    histogram['(']   = '%28';
    histogram[')']   = '%29';
    histogram['*']   = '%2A';
    histogram['~']   = '%7E';
    histogram['!']   = '%21';
    histogram['%20'] = '+';
    histogram['\u00DC'] = '%DC';
    histogram['\u00FC'] = '%FC';
    histogram['\u00C4'] = '%D4';
    histogram['\u00E4'] = '%E4';
    histogram['\u00D6'] = '%D6';
    histogram['\u00F6'] = '%F6';
    histogram['\u00DF'] = '%DF';
    histogram['\u20AC'] = '%80';
    histogram['\u0081'] = '%81';
    histogram['\u201A'] = '%82';
    histogram['\u0192'] = '%83';
    histogram['\u201E'] = '%84';
    histogram['\u2026'] = '%85';
    histogram['\u2020'] = '%86';
    histogram['\u2021'] = '%87';
    histogram['\u02C6'] = '%88';
    histogram['\u2030'] = '%89';
    histogram['\u0160'] = '%8A';
    histogram['\u2039'] = '%8B';
    histogram['\u0152'] = '%8C';
    histogram['\u008D'] = '%8D';
    histogram['\u017D'] = '%8E';
    histogram['\u008F'] = '%8F';
    histogram['\u0090'] = '%90';
    histogram['\u2018'] = '%91';
    histogram['\u2019'] = '%92';
    histogram['\u201C'] = '%93';
    histogram['\u201D'] = '%94';
    histogram['\u2022'] = '%95';
    histogram['\u2013'] = '%96';
    histogram['\u2014'] = '%97';
    histogram['\u02DC'] = '%98';
    histogram['\u2122'] = '%99';
    histogram['\u0161'] = '%9A';
    histogram['\u203A'] = '%9B';
    histogram['\u0153'] = '%9C';
    histogram['\u009D'] = '%9D';
    histogram['\u017E'] = '%9E';
    histogram['\u0178'] = '%9F';    
 
    for (unicodeStr in histogram) {
        hexEscStr = histogram[unicodeStr]; // Switch order when decoding
        ret = replacer(hexEscStr, unicodeStr, ret); // Custom replace. No regexing
    }
     
    ret = decodeURIComponent(ret);
		
    return ret;
}



function utf8_decode ( str_data ) {
    // Converts a UTF-8 encoded string to ISO-8859-1 
    //
    // version: 905.3122
    // discuss at: http://phpjs.org/functions/utf8_decode
    // +   original by: Webtoolkit.info (http://www.webtoolkit.info/)
    // +      input by: Aman Gupta
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Norman "zEh" Fuchs
    // +   bugfixed by: hitwork
    // +   bugfixed by: Onno Marsman
    // +      input by: Brett Zamir (http://brett-zamir.me)
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // *     example 1: utf8_decode('Kevin van Zonneveld');
    // *     returns 1: 'Kevin van Zonneveld'
    var tmp_arr = [], i = 0, ac = 0, c1 = 0, c2 = 0, c3 = 0;
     
    str_data += '';
     
    while ( i < str_data.length ) {
        c1 = str_data.charCodeAt(i);
        if (c1 < 128) {
            tmp_arr[ac++] = String.fromCharCode(c1);
            i++;
        } else if ((c1 > 191) && (c1 < 224)) {
            c2 = str_data.charCodeAt(i+1);
            tmp_arr[ac++] = String.fromCharCode(((c1 & 31) << 6) | (c2 & 63));
            i += 2;
        } else {
            c2 = str_data.charCodeAt(i+1);
            c3 = str_data.charCodeAt(i+2);
            tmp_arr[ac++] = String.fromCharCode(((c1 & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
            i += 3;
        }
    }
 
    return tmp_arr.join('');
}






function base64_decode( data ) {
    // Decodes string using MIME base64 algorithm 
    //
    // version: 905.3122
    // discuss at: http://phpjs.org/functions/base64_decode
    // +   original by: Tyler Akins (http://rumkin.com)
    // +   improved by: Thunder.m
    // +      input by: Aman Gupta
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: Onno Marsman
    // +   bugfixed by: Pellentesque Malesuada
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: Brett Zamir (http://brett-zamir.me)
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // -    depends on: utf8_decode
    // *     example 1: base64_decode('S2V2aW4gdmFuIFpvbm5ldmVsZA==');
    // *     returns 1: 'Kevin van Zonneveld'
    // mozilla has this native
    // - but breaks in 2.0.0.12!
    //if (typeof this.window['btoa'] == 'function') {
    //    return btoa(data);
    //}
 
    var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
    var o1, o2, o3, h1, h2, h3, h4, bits, i = 0, ac = 0, dec = "", tmp_arr = [];
 
    if (!data) {
        return data;
    }
 
    data += '';
 
    do {  // unpack four hexets into three octets using index points in b64
        h1 = b64.indexOf(data.charAt(i++));
        h2 = b64.indexOf(data.charAt(i++));
        h3 = b64.indexOf(data.charAt(i++));
        h4 = b64.indexOf(data.charAt(i++));
 
        bits = h1<<18 | h2<<12 | h3<<6 | h4;
 
        o1 = bits>>16 & 0xff;
        o2 = bits>>8 & 0xff;
        o3 = bits & 0xff;
 
        if (h3 == 64) {
            tmp_arr[ac++] = String.fromCharCode(o1);
        } else if (h4 == 64) {
            tmp_arr[ac++] = String.fromCharCode(o1, o2);
        } else {
            tmp_arr[ac++] = String.fromCharCode(o1, o2, o3);
        }
    } while (i < data.length);
 
    dec = tmp_arr.join('');
    dec = this.utf8_decode(dec);
 
    return dec;
}
function positionDialog(El) {	
	try {
		// make modal window for all content on window 
		if($(El)!==null && $(El).style !==undefined) {
			$(El).style.height= document.body.scrollHeight;
			// calculate middle of visible screen
			var t=window.innerHeight/2 - $(El).offsetHeight;
			var l=window.innerWidth/2 - $(El).offsetWidth/2;
			$(El).style.top=t + 'px';
			$(El).style.left=l + 'px';
			$(El).focus();
		}
		// scroll to top of page
		window.scrollTo(0, 0);
	} catch (Err) {
		alert(Err +'\n@'+Err.lineNumber);
	}
}