/* Basic */
function echo(output) {
	document.write(output);
}
function isset(var1) {
	
	var variable = var1;
	
	if (variable == undefined || variable == null) {
		return false;
	} else {
		return true;
	}
	
}
function changeClass(id, className) {
	$(id).className = className;
}
function noOnClick(id) {
	$(id).onclick = undefined;
}
function changeOnClick(id, func) {
	document.getElementById(id).onClick = func;
}
function empty(obj) {
	obj.innerHTML = '';
}

function openPopup(url, var_w, var_h) {
	
	/* Set defaults */
	if (var_w == null) 	{ var_w = 400; }
	if (var_h == null) 	{ var_h = 350; }
	
	window.open("https://cosmolearning.org/assets/popup/"+url,"mywindow","menubar=1,resizable=0,width="+var_w+",height="+var_h);

}
function goTo(url) {
	/* This function redirects to another URL */
	window.location = url;
}

/* AJAX */
function run(name, target, loader) {
	
	// Vars
	if (!isset(target)) { var target = null; }
	if (!isset(loader)) { var loader = null; }
	//if (!isset(onFinish)) { var onFinish = function(){}; }

	AJAX_run(name, { 'target':target, 'preloader':loader });
	
}

function getContent(name, params, options) {

	if (!isset(options)) {
		alert("Options param is required in getContent() javascript function.");
	}

	AJAX_getContent(name, params, options);
		
}

function deleteComment(id) {
	
	var agree = confirm("Are you sure you want to delete this comment?");

  if (agree) {
   
    	/* Remove Comment DIV */
    	commentDIV = $('comment-'+id);
    	destroy(commentDIV);
    
    	/* Delete Comment */    
    	AJAX_deleteComment(id, {'target':'messages','preloader':'loader'});
  	return true;
  	
  } else {
  	
		return false;
	
	}
	
}

function changeList(number, subject) {
	
	AJAX_EducationCoursesList(number, subject, {'target':'Available_Courses_inner_content','preloader':'big_loader'});
  
  /* Erase Previous One */
  $('Available_Courses_inner_content').innerHTML = '';
	
}

function changeList_cPanel(number) {
	
	AJAX_changeList_cPanel(number, subject, {'target':'New_Courses_inner_content','preloader':'big_loader'});
  
  /* Erase Previous One */
  $('Available_Courses_inner_content').innerHTML = '';
	
}
  
function saveImageFromSource(id, type) {
	
	openPopup('saveImageFromSRC.html'+"?id="+id+"&type="+type, 400, 180);
  /*AJAX_saveImageFromSRC(id, type, {'target':'saveImage_wrapper','preloader':'big_loader'});*/
	
}

function createSelectFieldFromValue(f, t, id) {
	if (thisValue !== '') {
      AJAX_createSelectFieldFromWHERE(field, type, thisValue, {'target':'new_field2','preloader':'small_loader'});    
  } else {
  	document.getElementById('new_field2').innerHTML = '';
  }
}
	
function countClicks(id, hash, current) {
	AJAX_countClicks(id, hash, current, {'target':'targeted'});
}
	
/* CSS */	
function updateID_fontWeight(id, v) {
		tagName = document.getElementById(id).tagName;
		idCount = document.getElementsByTagName(tagName).length;
		divs 		= document.getElementsByTagName(tagName);
		for (i = 0; i < idCount; i++) {
			if (divs[i].id == id) {	divs[i].style.fontWeight = v; }
		}		
	}
function updateID_className(id, v) {
		tagName = document.getElementById(id).tagName;
		idCount = document.getElementsByTagName(tagName).length;
		divs 		= document.getElementsByTagName(tagName);
		for (i = 0; i < idCount; i++) {
			if (divs[i].id == id) {	divs[i].className = v; }
		}		
	}

/* RATING */
function rate(id, type, rating) {
	
	/* If user hasn't already voted */
	if ($('rating_user_status').innerHTML !== 'Yes') {

		/* Change UL class */
		if (rating == '1') {
			$('rating_UL').className 	= 'rating onestar';
		} else if (rating == '2') {
			$('rating_UL').className 	= 'rating twostar';
		} else if (rating == '3') {
			$('rating_UL').className 	= 'rating threestar';
		} else if (rating == '4') { 
			$('rating_UL').className 	= 'rating fourstar';
		} else if (rating == '5') {
			$('rating_UL').className 	= 'rating fivestar';
		} else {
			$('rating_UL').className 	= 'rating fivestar';
		}

		AJAX_rate(id, type, rating, {	'target':'rating_msg',
										'preloader':'loader'
									});
		$('rating_hidden').innerHTML = '<b>Thanks for rating</b>';

	}
		
}
function rating_change_class_full(num) {

	if (num == '1') {
		$('rating_one').className 	= 'full';
		$('rating_two').className 	= '';
		$('rating_three').className = '';
		$('rating_four').className 	= '';
		$('rating_five').className 	= '';
	} else if (num == '2') {
		$('rating_one').className 	= 'full';
		$('rating_two').className 	= 'full';
		$('rating_three').className = '';
		$('rating_four').className 	= '';
		$('rating_five').className 	= '';
	} else if (num == '3') {
		$('rating_one').className 	= 'full';
		$('rating_two').className 	= 'full';
		$('rating_three').className = 'full';
		$('rating_four').className 	= '';
		$('rating_five').className 	= '';
	} else if (num == '4') {
		$('rating_one').className 	= 'full';
		$('rating_two').className 	= 'full';
		$('rating_three').className = 'full';
		$('rating_four').className 	= 'full';
		$('rating_five').className 	= '';
	} else if (num == '5') {
		$('rating_one').className 	= 'full';
		$('rating_two').className 	= 'full';
		$('rating_three').className = 'full';
		$('rating_four').className 	= 'full';
		$('rating_five').className 	= 'full';
	}
	
	return true;
	
}
function rating_change_class_empty() {
	
	$('rating_one').className 	= '';
	$('rating_two').className 	= '';
	$('rating_three').className = '';
	$('rating_four').className 	= '';
	$('rating_five').className 	= '';
	
	$('rating_msg').innerHTML 	= $('rating_hidden').innerHTML;
	
	return true;
	
}
function rating_loginCheck() {
	
	/* Already voted? */
	if ($('rating_user_status').innerHTML == 'Yes') {
		
		$('rating_msg').innerHTML = 'You\'ve already voted.';
	
	}
	
}
function rating_mouseOut() {
	//if (loggedIn()) {
		$('rating_msg').innerHTML = $('rating_hidden').innerHTML;
	//}
}
function rating_clean_error_msgs() {
	/* Remove any error messages */
	$('rating_msg').innerHTML = '';
}

/* Show/Hide */
function elementMakeVisible(id) {
	$(id).style.display = '';
	$(id).style.visibility = 'visible';
	$(id).style.opacity = 1;
	$(id).style.filter = 'alpha(opacity=100)';
}
function elementHidden(id) {
	if ($(id).style.display == 'none' || $(id).style.visibility == 'hidden' || $(id).style.opacity == (0|'0')) {
		return true;
	} else {
		return false;
	}
}
function elementShow(id, dur) {
	
	// Vars
	if (!isset(dur)) { var dur = null; }
	
	// Effect
	if (dur == null) {
		elementMakeVisible(id);
	} else {
		opacity(id, 0, 1, 0);
		elementMakeVisible(id);
		opacity(id, dur, 0, 1);
	}
	
}
function elementHide(id, dur) {
	
	// Vars
	if (!isset(dur)) { var dur = null; }
	
	// Effect
	if (dur == null) {
		$(id).setStyle({display: 'none'});
	} else {
		opacity(id, 0, 0, 1);
		opacity(id, dur, 1, 0);
		setTimeout("$('"+id+"').setStyle({display: ''});", (dur*1000)+500);
	}
	
}

/* ANIMATION */
function pageOpacity(opac, dur) {
	
	// Vars
	if (opac == 0) { var disp = 'none'; } else { var disp = ''; }
	if (!isset(dur)) { var dur = null; }
	
	if (dur == null) {
		$('page_opacity').setStyle({
			display: disp,
			opacity: 0.2
		});
	} else {
		deleteFadeOut('page_opacity', dur);
	}
	
}
function showHide(id) {
	
	var dur = 0.5;
	
	if ($(id).style.display == 'none') {
		$(id).setStyle({visibility: 'visible', display: '', opacity: 0});
		new Effect.Opacity(
		   id, { 
		      from: 0.0, 
		      to: 1.0,
		      duration: dur
		   }
		);
	} else {
		$(id).fade({ duration: dur });
	}
	
}
function fadeOut(id, duration) {	
	opacity(id, duration, 1.0, 0);
}
function fadeIn(id, duration) {
	
	opacity(id, duration, 0, 1.0);
	
}
function opacity(id, duration, from, to) {
	
	/* Defaults */
	if (!isset(duration)) {
		duration = 0.5;
	} else if (!isset(from)) {
		from = 1.0;
	} else if (!isset(to)) {
		to = 0;
	}
	
	new Effect.Opacity(id, { from: from, to: to, duration: duration });
}
function deleteFadeOut(id, duration) {
	
	/* Default duration */
	if (isset(duration)) {
		duration = '0.5';
	}

	new Effect.Fade(id, { duration: duration });
	
}
function destroy(id, durationNum) {
	if (!isset(durationNum)) { durationNum = 0; }
	new Effect.Fade(id, { duration: durationNum });
}
function morph(id, styles, dur) {

	/* Not Working */
	
	if (!isset(dur)) { var dur = 1.0; }
	
	new Effect.Morph(id, {
	  style: styles,
	  duration: dur
	});

}

/* DICTIONARY */
function getSelText() {
	
	var txt = '';
	/* Get the selected text in the current document. */
	text = (document.all) ? document.selection.createRange().text : document.getSelection();
	
	/* Decide what to do with the selected text. In this case, it will go inside a DIV. */
	AJAX_Dictionary(text, {'target':'selectedText','preloader':'loader'});
	/*$('selectedText').innerHTML = txt;*/

}

/* FIRST PAGE */
function changeSidebar(type, id_this) {
	$('handler_heading').className = '';
	id_this.className = 'selected';
	if ($('recent_added_current').innerHTML != type) {
		$('recent_added_current').innerHTML = type;
		Effect.toggle('recent_added_interior', 'appear', { duration: 0.25 });
		setTimeout("$('recent_added_interior').innerHTML = $('recent_added_"+type+"').innerHTML; Effect.toggle('recent_added_interior', 'appear', { duration: 0.25 });", 300);
	}
}

/* NEWS TICKER */
function new_newsTicker(pe) {
	
	var limit 				= 5;
	var time 					= 2; // 1
	var anim_duration = 0.25;
	
	/* News Ticker */
	var i = parseFloat($('ticker_number').value);
	if (i <= limit) {
		fadeOut("ticker_title", anim_duration);
		fadeOut("ticker_date", anim_duration);
		setTimeout("$('ticker_title').innerHTML = $('ticker_post_"+i+"').value;$('ticker_date').innerHTML = $('ticker_post_"+i+"_date').value;fadeIn('ticker_title', "+anim_duration+");fadeIn('ticker_date', "+anim_duration+");$('ticker_number').value = "+i+"+1;", (time*100)+100);
	} else {
		$('ticker_number').value = 1;
		var i = parseFloat($('ticker_number').value);
		fadeOut("ticker_title", anim_duration);
		fadeOut("ticker_date", anim_duration);
		setTimeout("$('ticker_title').innerHTML = $('ticker_post_"+i+"').value;$('ticker_date').innerHTML = $('ticker_post_"+i+"_date').value;fadeIn('ticker_title', "+anim_duration+");fadeIn('ticker_date', "+anim_duration+");$('ticker_number').value = "+i+"+1;", (time*100)+100);
	}
	
	/* Highlights */
	var highlights_i = parseFloat($('highlights_number').value);
	var total = parseFloat($('highlight_total_num').value);
	
	fadeOut('highlights', anim_duration);
	setTimeout("$('highlights').style.backgroundColor = 'black';$('highlights').style.backgroundImage = $('highlight_bgimage_"+highlights_i+"').value;$('highlights').style.backgroundPosition = 'center center';$('highlights').style.backgroundRepeat = 'no-repeat';$('highlight_link').href = $('highlight_link_"+highlights_i+"').value;$('highlight_link').title = $('highlight_title_"+highlights_i+"').value;$('highlight_title').innerHTML = $('highlight_title_"+highlights_i+"').value;$('highlight_subject').innerHTML = $('highlight_subject_"+highlights_i+"').value;$('highlight_contributor').innerHTML = $('highlight_contributor_"+highlights_i+"').value;fadeIn('highlights', "+anim_duration+");", (time*100)+100);
	if (highlights_i != total) {
		$('highlights_number').value = highlights_i+1;
	} else {
		$('highlights_number').value = 1;
	}
	
}
function new_newsTicker_only_highlights(pe) {
	
	var limit = 5;
	var time = 2;
	var anim_duration = 0.25; 
	
	/* Highlights */
	var highlights_i = parseFloat($('highlights_number').value);
	var total = parseFloat($('highlight_total_num').value);
	
	fadeOut('highlights', anim_duration);
	setTimeout("$('highlights').style.backgroundColor = 'black';$('highlights').style.backgroundImage = $('highlight_bgimage_"+highlights_i+"').value;$('highlights').style.backgroundPosition = 'center center';$('highlights').style.backgroundRepeat = 'no-repeat';$('highlight_link').href = $('highlight_link_"+highlights_i+"').value;$('highlight_link').title = $('highlight_title_"+highlights_i+"').value;$('highlight_title').innerHTML = $('highlight_title_"+highlights_i+"').value;fadeIn('highlights', "+anim_duration+");", (time*100)+100);
	if (highlights_i != total) {
		$('highlights_number').value = highlights_i+1;
	} else {
		$('highlights_number').value = 2;
	}
	
}

function newsTicker() {
	new PeriodicalExecuter(new_newsTicker, 5);
}
function newsTicker_only_highlights() {
	new PeriodicalExecuter(new_newsTicker_only_highlights, 5);
}

/* COOKIES */
function loggedIn() {
	if (getCookie('login')) {
		return true;
	} else {
		return false;
	}
}
function getCookie(c_name)
{
if (document.cookie.length>0)
  {
  c_start=document.cookie.indexOf(c_name + "=");
  if (c_start!=-1)
    { 
    c_start=c_start + c_name.length+1; 
    c_end=document.cookie.indexOf(";",c_start);
    if (c_end==-1) c_end=document.cookie.length;
    return unescape(document.cookie.substring(c_start,c_end));
    } 
  }
return "";
}

/* DIM THE LIGHTS */
function dimTheLights() {
	
	$('page_darker').style.display = '';
	opacity('page_darker', 1.0, 0, 0.9);
	/*$('page_darker').style.display = '';*/

}
function dimTheLightsBack() {

	/*opacity('page_darker', 1.0, 0.9, 0);
	setTimeout("$('page_darker').setStyle({ display: 'none';});", 1200);*/
	deleteFadeOut('page_darker', 1.0);

}
function openExplandablePopup(title, video) {
	
	window.open('https://cosmolearning.org/'+'videopopup?title='+title+'&vid='+video, null, 'toolbar=no,scrollbars=no,location=no,statusbar=no,menubar=no,resizable=no,width=640,height=350')

}

function see_more(id, id2) {
	$(id).innerHTML = $(id2).innerHTML;
}



function addslashes (str) {
    // http://kevin.vanzonneveld.net
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Ates Goral (http://magnetiq.com)
    // +   improved by: marrtins
    // +   improved by: Nate
    // +   improved by: Onno Marsman
    // +   input by: Denny Wardhana
    // +   improved by: Brett Zamir (http://brett-zamir.me)
    // +   improved by: Oskar Larsson Högfeldt (http://oskar-lh.name/)
    // *     example 1: addslashes("kevin's birthday");
    // *     returns 1: 'kevin\'s birthday'
 
    return (str+'').replace(/[\\"']/g, '\\$&').replace(/\u0000/g, '\\0');
}
function htmlspecialchars (string, quote_style, charset, double_encode) {
    // http://kevin.vanzonneveld.net
    // +   original by: Mirek Slugen
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: Nathan
    // +   bugfixed by: Arno
    // +    revised by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +    bugfixed by: Brett Zamir (http://brett-zamir.me)
    // +      input by: Ratheous
    // +      input by: Mailfaker (http://www.weedem.fr/)
    // +      reimplemented by: Brett Zamir (http://brett-zamir.me)
    // +      input by: felix
    // +    bugfixed by: Brett Zamir (http://brett-zamir.me)
    // %        note 1: charset argument not supported
    // *     example 1: htmlspecialchars("<a href='test'>Test</a>", 'ENT_QUOTES');
    // *     returns 1: '&lt;a href=&#039;test&#039;&gt;Test&lt;/a&gt;'
    // *     example 2: htmlspecialchars("ab\"c'd", ['ENT_NOQUOTES', 'ENT_QUOTES']);
    // *     returns 2: 'ab"c&#039;d'
    // *     example 3: htmlspecialchars("my "&entity;" is still here", null, null, false);
    // *     returns 3: 'my &quot;&entity;&quot; is still here'

    var optTemp = 0, i = 0, noquotes= false;
    if (typeof quote_style === 'undefined' || quote_style === null) {
        quote_style = 2;
    }
    string = string.toString();
    if (double_encode !== false) { // Put this first to avoid double-encoding
        string = string.replace(/&/g, '&amp;');
    }
    string = string.replace(/</g, '&lt;').replace(/>/g, '&gt;');

    var OPTS = {
        'ENT_NOQUOTES': 0,
        'ENT_HTML_QUOTE_SINGLE' : 1,
        'ENT_HTML_QUOTE_DOUBLE' : 2,
        'ENT_COMPAT': 2,
        'ENT_QUOTES': 3,
        'ENT_IGNORE' : 4
    };
    if (quote_style === 0) {
        noquotes = true;
    }
    if (typeof quote_style !== 'number') { // Allow for a single string or an array of string flags
        quote_style = [].concat(quote_style);
        for (i=0; i < quote_style.length; i++) {
            // Resolve string input to bitwise e.g. 'PATHINFO_EXTENSION' becomes 4
            if (OPTS[quote_style[i]] === 0) {
                noquotes = true;
            }
            else if (OPTS[quote_style[i]]) {
                optTemp = optTemp | OPTS[quote_style[i]];
            }
        }
        quote_style = optTemp;
    }
    if (quote_style & OPTS.ENT_HTML_QUOTE_SINGLE) {
        string = string.replace(/'/g, '&#039;');
    }
    if (!noquotes) {
        string = string.replace(/"/g, '&quot;');
    }

    return string;
}
function htmlspecialchars_decode (string, quote_style) {
    // http://kevin.vanzonneveld.net
    // +   original by: Mirek Slugen
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: Mateusz "loonquawl" Zalega
    // +      input by: ReverseSyntax
    // +      input by: Slawomir Kaniecki
    // +      input by: Scott Cariss
    // +      input by: Francois
    // +   bugfixed by: Onno Marsman
    // +    revised by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: Brett Zamir (http://brett-zamir.me)
    // +      input by: Ratheous
    // +      input by: Mailfaker (http://www.weedem.fr/)
    // +      reimplemented by: Brett Zamir (http://brett-zamir.me)
    // +    bugfixed by: Brett Zamir (http://brett-zamir.me)
    // *     example 1: htmlspecialchars_decode("<p>this -&gt; &quot;</p>", 'ENT_NOQUOTES');
    // *     returns 1: '<p>this -> &quot;</p>'
    // *     example 2: htmlspecialchars_decode("&amp;quot;");
    // *     returns 2: '&quot;'

    var optTemp = 0, i = 0, noquotes= false;
    if (typeof quote_style === 'undefined') {
        quote_style = 2;
    }
    string = string.toString().replace(/&lt;/g, '<').replace(/&gt;/g, '>');
    var OPTS = {
        'ENT_NOQUOTES': 0,
        'ENT_HTML_QUOTE_SINGLE' : 1,
        'ENT_HTML_QUOTE_DOUBLE' : 2,
        'ENT_COMPAT': 2,
        'ENT_QUOTES': 3,
        'ENT_IGNORE' : 4
    };
    if (quote_style === 0) {
        noquotes = true;
    }
    if (typeof quote_style !== 'number') { // Allow for a single string or an array of string flags
        quote_style = [].concat(quote_style);
        for (i=0; i < quote_style.length; i++) {
            // Resolve string input to bitwise e.g. 'PATHINFO_EXTENSION' becomes 4
            if (OPTS[quote_style[i]] === 0) {
                noquotes = true;
            }
            else if (OPTS[quote_style[i]]) {
                optTemp = optTemp | OPTS[quote_style[i]];
            }
        }
        quote_style = optTemp;
    }
    if (quote_style & OPTS.ENT_HTML_QUOTE_SINGLE) {
        string = string.replace(/&#0*39;/g, "'"); // PHP doesn't currently escape if more than one 0, but it should
        // string = string.replace(/&apos;|&#x0*27;/g, "'"); // This would also be useful here, but not a part of PHP
    }
    if (!noquotes) {
        string = string.replace(/&quot;/g, '"');
    }
    // Put this in last place to avoid escape being double-decoded
    string = string.replace(/&amp;/g, '&');

    return string;
}
function htmlentities(string, quote_style) {

    var hash_map = {}, symbol = '', tmp_str = '', entity = '';
    tmp_str = string.toString();
    
    if (false === (hash_map = this.get_html_translation_table('HTML_ENTITIES', quote_style))) {
        return false;
    }
    hash_map["'"] = '&#039;';
    for (symbol in hash_map) {
        entity = hash_map[symbol];
        tmp_str = tmp_str.split(symbol).join(entity);
    }
    
    return tmp_str;
}
function str_replace (search, replace, subject, count) {
    // http://kevin.vanzonneveld.net
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Gabriel Paderni
    // +   improved by: Philip Peterson
    // +   improved by: Simon Willison (http://simonwillison.net)
    // +    revised by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
    // +   bugfixed by: Anton Ongson
    // +      input by: Onno Marsman
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +    tweaked by: Onno Marsman
    // +      input by: Brett Zamir (http://brett-zamir.me)
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   input by: Oleg Eremeev
    // +   improved by: Brett Zamir (http://brett-zamir.me)
    // +   bugfixed by: Oleg Eremeev
    // %          note 1: The count parameter must be passed as a string in order
    // %          note 1:  to find a global variable in which the result will be given
    // *     example 1: str_replace(' ', '.', 'Kevin van Zonneveld');
    // *     returns 1: 'Kevin.van.Zonneveld'
    // *     example 2: str_replace(['{name}', 'l'], ['hello', 'm'], '{name}, lars');
    // *     returns 2: 'hemmo, mars'

    var i = 0, j = 0, temp = '', repl = '', sl = 0, fl = 0,
            f = [].concat(search),
            r = [].concat(replace),
            s = subject,
            ra = r instanceof Array, sa = s instanceof Array;
    s = [].concat(s);
    if (count) {
        this.window[count] = 0;
    }

    for (i=0, sl=s.length; i < sl; i++) {
        if (s[i] === '') {
            continue;
        }
        for (j=0, fl=f.length; j < fl; j++) {
            temp = s[i]+'';
            repl = ra ? (r[j] !== undefined ? r[j] : '') : r[0];
            s[i] = (temp).split(f[j]).join(repl);
            if (count && s[i] !== temp) {
                this.window[count] += (temp.length-s[i].length)/f[j].length;}
        }
    }
    return sa ? s : s[0];
}
function stripslashes (str) {
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Ates Goral (http://magnetiq.com)
    // +      fixed by: Mick@el
    // +   improved by: marrtins
    // +   bugfixed by: Onno Marsman
    // +   improved by: rezna
    // +   input by: Rick Waldron
    // +   reimplemented by: Brett Zamir (http://brett-zamir.me)
    // +   input by: Brant Messenger (http://www.brantmessenger.com/)
    // +   bugfixed by: Brett Zamir (http://brett-zamir.me)
    // *     example 1: stripslashes('Kevin\'s code');
    // *     returns 1: "Kevin's code"
    // *     example 2: stripslashes('Kevin\\\'s code');
    // *     returns 2: "Kevin\'s code"
    return (str+'').replace(/\\(.?)/g, function (s, n1) {
        switch (n1) {
            case '\\':
                return '\\';
            case '0':
                return '\u0000';
            case '':
                return '';
            default:
                return n1;
        }
    });
}
function base64_decode (data) {
    // http://kevin.vanzonneveld.net
    // +   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 base64_encode (data) {
    // http://kevin.vanzonneveld.net
    // +   original by: Tyler Akins (http://rumkin.com)
    // +   improved by: Bayron Guevara
    // +   improved by: Thunder.m
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: Pellentesque Malesuada
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // -    depends on: utf8_encode
    // *     example 1: base64_encode('Kevin van Zonneveld');
    // *     returns 1: 'S2V2aW4gdmFuIFpvbm5ldmVsZA=='

    // mozilla has this native
    // - but breaks in 2.0.0.12!
    //if (typeof this.window['atob'] == 'function') {
    //    return atob(data);
    //}
        
    var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
    var o1, o2, o3, h1, h2, h3, h4, bits, i = 0, ac = 0, enc="", tmp_arr = [];

    if (!data) {
        return data;
    }

    data = this.utf8_encode(data+'');
    
    do { // pack three octets into four hexets
        o1 = data.charCodeAt(i++);
        o2 = data.charCodeAt(i++);
        o3 = data.charCodeAt(i++);

        bits = o1<<16 | o2<<8 | o3;

        h1 = bits>>18 & 0x3f;
        h2 = bits>>12 & 0x3f;
        h3 = bits>>6 & 0x3f;
        h4 = bits & 0x3f;

        // use hexets to index into b64, and append result to encoded string
        tmp_arr[ac++] = b64.charAt(h1) + b64.charAt(h2) + b64.charAt(h3) + b64.charAt(h4);
    } while (i < data.length);
    
    enc = tmp_arr.join('');
    
    switch (data.length % 3) {
        case 1:
            enc = enc.slice(0, -2) + '==';
        break;
        case 2:
            enc = enc.slice(0, -1) + '=';
        break;
    }

    return enc;
}
function utf8_decode ( str_data ) {
    // http://kevin.vanzonneveld.net
    // +   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 utf8_encode ( argString ) {
    // http://kevin.vanzonneveld.net
    // +   original by: Webtoolkit.info (http://www.webtoolkit.info/)
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: sowberry
    // +    tweaked by: Jack
    // +   bugfixed by: Onno Marsman
    // +   improved by: Yves Sucaet
    // +   bugfixed by: Onno Marsman
    // +   bugfixed by: Ulrich
    // *     example 1: utf8_encode('Kevin van Zonneveld');
    // *     returns 1: 'Kevin van Zonneveld'

    var string = (argString+''); // .replace(/\r\n/g, "\n").replace(/\r/g, "\n");

    var utftext = "";
    var start, end;
    var stringl = 0;

    start = end = 0;
    stringl = string.length;
    for (var n = 0; n < stringl; n++) {
        var c1 = string.charCodeAt(n);
        var enc = null;

        if (c1 < 128) {
            end++;
        } else if (c1 > 127 && c1 < 2048) {
            enc = String.fromCharCode((c1 >> 6) | 192) + String.fromCharCode((c1 & 63) | 128);
        } else {
            enc = String.fromCharCode((c1 >> 12) | 224) + String.fromCharCode(((c1 >> 6) & 63) | 128) + String.fromCharCode((c1 & 63) | 128);
        }
        if (enc !== null) {
            if (end > start) {
                utftext += string.substring(start, end);
            }
            utftext += enc;
            start = end = n+1;
        }
    }

    if (end > start) {
        utftext += string.substring(start, string.length);
    }

    return utftext;
}

function get_html_translation_table (table, quote_style) {
    // http://kevin.vanzonneveld.net
    // +   original by: Philip Peterson
    // +    revised by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: noname
    // +   bugfixed by: Alex
    // +   bugfixed by: Marco
    // +   bugfixed by: madipta
    // +   improved by: KELAN
    // +   improved by: Brett Zamir (http://brett-zamir.me)
    // +   bugfixed by: Brett Zamir (http://brett-zamir.me)
    // +      input by: Frank Forte
    // +   bugfixed by: T.Wild
    // +      input by: Ratheous
    // %          note: It has been decided that we're not going to add global
    // %          note: dependencies to php.js, meaning the constants are not
    // %          note: real constants, but strings instead. Integers are also supported if someone
    // %          note: chooses to create the constants themselves.
    // *     example 1: get_html_translation_table('HTML_SPECIALCHARS');
    // *     returns 1: {'"': '&quot;', '&': '&amp;', '<': '&lt;', '>': '&gt;'}
    
    var entities = {}, hash_map = {}, decimal = 0, symbol = '';
    var constMappingTable = {}, constMappingQuoteStyle = {};
    var useTable = {}, useQuoteStyle = {};
    
    // Translate arguments
    constMappingTable[0]      = 'HTML_SPECIALCHARS';
    constMappingTable[1]      = 'HTML_ENTITIES';
    constMappingQuoteStyle[0] = 'ENT_NOQUOTES';
    constMappingQuoteStyle[2] = 'ENT_COMPAT';
    constMappingQuoteStyle[3] = 'ENT_QUOTES';

    useTable       = !isNaN(table) ? constMappingTable[table] : table ? table.toUpperCase() : 'HTML_SPECIALCHARS';
    useQuoteStyle = !isNaN(quote_style) ? constMappingQuoteStyle[quote_style] : quote_style ? quote_style.toUpperCase() : 'ENT_COMPAT';

    if (useTable !== 'HTML_SPECIALCHARS' && useTable !== 'HTML_ENTITIES') {
        throw new Error("Table: "+useTable+' not supported');
        // return false;
    }

    entities['38'] = '&amp;';
    if (useTable === 'HTML_ENTITIES') {
        entities['160'] = '&nbsp;';
        entities['161'] = '&iexcl;';
        entities['162'] = '&cent;';
        entities['163'] = '&pound;';
        entities['164'] = '&curren;';
        entities['165'] = '&yen;';
        entities['166'] = '&brvbar;';
        entities['167'] = '&sect;';
        entities['168'] = '&uml;';
        entities['169'] = '&copy;';
        entities['170'] = '&ordf;';
        entities['171'] = '&laquo;';
        entities['172'] = '&not;';
        entities['173'] = '&shy;';
        entities['174'] = '&reg;';
        entities['175'] = '&macr;';
        entities['176'] = '&deg;';
        entities['177'] = '&plusmn;';
        entities['178'] = '&sup2;';
        entities['179'] = '&sup3;';
        entities['180'] = '&acute;';
        entities['181'] = '&micro;';
        entities['182'] = '&para;';
        entities['183'] = '&middot;';
        entities['184'] = '&cedil;';
        entities['185'] = '&sup1;';
        entities['186'] = '&ordm;';
        entities['187'] = '&raquo;';
        entities['188'] = '&frac14;';
        entities['189'] = '&frac12;';
        entities['190'] = '&frac34;';
        entities['191'] = '&iquest;';
        entities['192'] = '&Agrave;';
        entities['193'] = '&Aacute;';
        entities['194'] = '&Acirc;';
        entities['195'] = '&Atilde;';
        entities['196'] = '&Auml;';
        entities['197'] = '&Aring;';
        entities['198'] = '&AElig;';
        entities['199'] = '&Ccedil;';
        entities['200'] = '&Egrave;';
        entities['201'] = '&Eacute;';
        entities['202'] = '&Ecirc;';
        entities['203'] = '&Euml;';
        entities['204'] = '&Igrave;';
        entities['205'] = '&Iacute;';
        entities['206'] = '&Icirc;';
        entities['207'] = '&Iuml;';
        entities['208'] = '&ETH;';
        entities['209'] = '&Ntilde;';
        entities['210'] = '&Ograve;';
        entities['211'] = '&Oacute;';
        entities['212'] = '&Ocirc;';
        entities['213'] = '&Otilde;';
        entities['214'] = '&Ouml;';
        entities['215'] = '&times;';
        entities['216'] = '&Oslash;';
        entities['217'] = '&Ugrave;';
        entities['218'] = '&Uacute;';
        entities['219'] = '&Ucirc;';
        entities['220'] = '&Uuml;';
        entities['221'] = '&Yacute;';
        entities['222'] = '&THORN;';
        entities['223'] = '&szlig;';
        entities['224'] = '&agrave;';
        entities['225'] = '&aacute;';
        entities['226'] = '&acirc;';
        entities['227'] = '&atilde;';
        entities['228'] = '&auml;';
        entities['229'] = '&aring;';
        entities['230'] = '&aelig;';
        entities['231'] = '&ccedil;';
        entities['232'] = '&egrave;';
        entities['233'] = '&eacute;';
        entities['234'] = '&ecirc;';
        entities['235'] = '&euml;';
        entities['236'] = '&igrave;';
        entities['237'] = '&iacute;';
        entities['238'] = '&icirc;';
        entities['239'] = '&iuml;';
        entities['240'] = '&eth;';
        entities['241'] = '&ntilde;';
        entities['242'] = '&ograve;';
        entities['243'] = '&oacute;';
        entities['244'] = '&ocirc;';
        entities['245'] = '&otilde;';
        entities['246'] = '&ouml;';
        entities['247'] = '&divide;';
        entities['248'] = '&oslash;';
        entities['249'] = '&ugrave;';
        entities['250'] = '&uacute;';
        entities['251'] = '&ucirc;';
        entities['252'] = '&uuml;';
        entities['253'] = '&yacute;';
        entities['254'] = '&thorn;';
        entities['255'] = '&yuml;';
    }

    if (useQuoteStyle !== 'ENT_NOQUOTES') {
        entities['34'] = '&quot;';
    }
    if (useQuoteStyle === 'ENT_QUOTES') {
        entities['39'] = '&#39;';
    }
    entities['60'] = '&lt;';
    entities['62'] = '&gt;';


    // ascii decimals to real symbols
    for (decimal in entities) {
        symbol = String.fromCharCode(decimal);
        hash_map[symbol] = entities[decimal];
    }
    
    return hash_map;
}



/* Edit In Place */
function editInPlace(id, func) {
	
	var innerContent = trim($('editInPlace_id'+id).innerHTML);
	var buttons = '<input type="button" value="Save" onClick="editInPlace_save(\''+id+'\', \''+func+'\')" /> <input type="button" value="Cancel" onClick="editInPlace_cancel(\''+id+'\', \''+innerContent+'\');" />';

	$('editInPlace_wrapper_id'+id).innerHTML = '<div id="editInPlace_id'+id+'" onClick="" class="">'+'<textarea id="editInPlace_textarea_id'+id+'" class="editable_area">'+innerContent+'</textarea><br>'+buttons+'</div>';
	
}
function editInPlace_save(id, func) {
	
	var newContent = $('editInPlace_textarea_id'+id).value;
	editInPlace_cancel(id, newContent);
	
	// Save value
	var func = base64_decode(func);
	var func = str_replace('e339b6f7684645b08dea88d5ab7ea8b8ffaac3ccPz8/Pz8/Pz8/Pw==', newContent, func);
	eval(func);
		
}
function editInPlace_cancel(id, orig_content) {

	$('editInPlace_wrapper_id'+id).innerHTML = '<div id="editInPlace_id'+id+'" onClick="editInPlace(\''+id+'\')" class="editable">'+orig_content+'</div>';
	
}

/* Global Autosuggest */
function globalAutosuggest(_this, func, delayTime) {
	
	elementShow('globalsearch_suggestions');
	
	if (!isset(keyUpTimer)) { var keyUpTimer = new Object(); }
	clearTimeout(keyUpTimer);
	  
	var value = _this.value;
	var func = base64_decode(func);
	var func = str_replace('e339b6f7684645b08dea88d5ab7ea8b8ffaac3ccPz8/Pz8/Pz8/Pw==', value, func);
	eval(func);
	 
	//keyUpTimer = setTimeout(func,1000); // will activate when the user has stopped typing for 1 second
	
	/*if (lastTyped()) {
		var value = _this.value;
		var func = base64_decode(func);
		var func = str_replace('e339b6f7684645b08dea88d5ab7ea8b8ffaac3ccPz8/Pz8/Pz8/Pw==', value, func);
		eval(func);
	}*/
	
}
function globalAutosuggest_doIt(blnDelay) {
	
	/*
	IMPROVED:
	
	var objDelay = new Object();
	var delayTime = 1000;
	function doSomething(blnDelay){
	  if (blnDelay == null) {
	    clearTimeout(objDelay);
	    objDelay = setTimeout('doSomething(true)',delayTime);
	  } else {
	  	// 10 seconds since last keyup have past
	    var value = _this.value;
			var func = base64_decode(func);
			var func = str_replace('e339b6f7684645b08dea88d5ab7ea8b8ffaac3ccPz8/Pz8/Pz8/Pw==', value, func);
			eval(func);
	  }
	}
	
	*/
	
}



function serialize( mixed_value ) {
    var _getType = function( inp ) {
        var type = typeof inp, match;
        var key;
        if (type == 'object' && !inp) {
            return 'null';
        }
        if (type == "object") {
            if (!inp.constructor) {
                return 'object';
            }
            var cons = inp.constructor.toString();
            match = cons.match(/(\w+)\(/);
            if (match) {
                cons = match[1].toLowerCase();
            }
            var types = ["boolean", "number", "string", "array"];
            for (key in types) {
                if (cons == types[key]) {
                    type = types[key];
                    break;
                }
            }
        }
        return type;
    };
    var type = _getType(mixed_value);
    var val, ktype = '';
    
    switch (type) {
        case "function": 
            val = ""; 
            break;
        case "undefined":
            val = "N";
            break;
        case "boolean":
            val = "b:" + (mixed_value ? "1" : "0");
            break;
        case "number":
            val = (Math.round(mixed_value) == mixed_value ? "i" : "d") + ":" + mixed_value;
            break;
        case "string":
            val = "s:" + mixed_value.length + ":\"" + mixed_value + "\"";
            break;
        case "array":
        case "object":
            val = "a";
            var count = 0;
            var vals = "";
            var okey;
            var key;
            for (key in mixed_value) {
                ktype = _getType(mixed_value[key]);
                if (ktype == "function") { 
                    continue; 
                }
                
                okey = (key.match(/^[0-9]+$/) ? parseInt(key, 10) : key);
                vals += serialize(okey) +
                        serialize(mixed_value[key]);
                count++;
            }
            val += ":" + count + ":{" + vals + "}";
            break;
    }
    if (type != "object" && type != "array") {
      val += ";";
  }
    return val;
}



function frameworksCheck() {
	
	/* Prototype */
	if (jQuery) {  
	  // jQuery is loaded
		alert('jQuery is loaded!');
	} else {
	  // jQuery is not loaded
		alert('jQuery is NOT loaded!');
	}
	
	/* Prototype */
	if (Prototype) {  
	  // Prototype is loaded
		alert('Prototype is loaded!');
	} else {
	  // Prototype is not loaded
		alert('Prototype is NOT loaded!');
	}
	
}



function trim(str) {

	return str.replace(/^\s+|\s+$/g,"");

}



//v1.7
// Flash Player Version Detection
// Detect Client Browser type
// Copyright 2005-2007 Adobe Systems Incorporated.  All rights reserved.
var isIE  = (navigator.appVersion.indexOf("MSIE") != -1) ? true : false;
var isWin = (navigator.appVersion.toLowerCase().indexOf("win") != -1) ? true : false;
var isOpera = (navigator.userAgent.indexOf("Opera") != -1) ? true : false;

function ControlVersion()
{
	var version;
	var axo;
	var e;

	// NOTE : new ActiveXObject(strFoo) throws an exception if strFoo isn't in the registry

	try {
		// version will be set for 7.X or greater players
		axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7");
		version = axo.GetVariable("$version");
	} catch (e) {
	}

	if (!version)
	{
		try {
			// version will be set for 6.X players only
			axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.6");
			
			// installed player is some revision of 6.0
			// GetVariable("$version") crashes for versions 6.0.22 through 6.0.29,
			// so we have to be careful. 
			
			// default to the first public version
			version = "WIN 6,0,21,0";

			// throws if AllowScripAccess does not exist (introduced in 6.0r47)		
			axo.AllowScriptAccess = "always";

			// safe to call for 6.0r47 or greater
			version = axo.GetVariable("$version");

		} catch (e) {
		}
	}

	if (!version)
	{
		try {
			// version will be set for 4.X or 5.X player
			axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.3");
			version = axo.GetVariable("$version");
		} catch (e) {
		}
	}

	if (!version)
	{
		try {
			// version will be set for 3.X player
			axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.3");
			version = "WIN 3,0,18,0";
		} catch (e) {
		}
	}

	if (!version)
	{
		try {
			// version will be set for 2.X player
			axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash");
			version = "WIN 2,0,0,11";
		} catch (e) {
			version = -1;
		}
	}
	
	return version;
}

// JavaScript helper required to detect Flash Player PlugIn version information
function GetSwfVer(){
	// NS/Opera version >= 3 check for Flash plugin in plugin array
	var flashVer = -1;
	
	if (navigator.plugins != null && navigator.plugins.length > 0) {
		if (navigator.plugins["Shockwave Flash 2.0"] || navigator.plugins["Shockwave Flash"]) {
			var swVer2 = navigator.plugins["Shockwave Flash 2.0"] ? " 2.0" : "";
			var flashDescription = navigator.plugins["Shockwave Flash" + swVer2].description;
			var descArray = flashDescription.split(" ");
			var tempArrayMajor = descArray[2].split(".");			
			var versionMajor = tempArrayMajor[0];
			var versionMinor = tempArrayMajor[1];
			var versionRevision = descArray[3];
			if (versionRevision == "") {
				versionRevision = descArray[4];
			}
			if (versionRevision[0] == "d") {
				versionRevision = versionRevision.substring(1);
			} else if (versionRevision[0] == "r") {
				versionRevision = versionRevision.substring(1);
				if (versionRevision.indexOf("d") > 0) {
					versionRevision = versionRevision.substring(0, versionRevision.indexOf("d"));
				}
			}
			var flashVer = versionMajor + "." + versionMinor + "." + versionRevision;
		}
	}
	// MSN/WebTV 2.6 supports Flash 4
	else if (navigator.userAgent.toLowerCase().indexOf("webtv/2.6") != -1) flashVer = 4;
	// WebTV 2.5 supports Flash 3
	else if (navigator.userAgent.toLowerCase().indexOf("webtv/2.5") != -1) flashVer = 3;
	// older WebTV supports Flash 2
	else if (navigator.userAgent.toLowerCase().indexOf("webtv") != -1) flashVer = 2;
	else if ( isIE && isWin && !isOpera ) {
		flashVer = ControlVersion();
	}	
	return flashVer;
}

// When called with reqMajorVer, reqMinorVer, reqRevision returns true if that version or greater is available
function DetectFlashVer(reqMajorVer, reqMinorVer, reqRevision)
{
	versionStr = GetSwfVer();
	if (versionStr == -1 ) {
		return false;
	} else if (versionStr != 0) {
		if(isIE && isWin && !isOpera) {
			// Given "WIN 2,0,0,11"
			tempArray         = versionStr.split(" "); 	// ["WIN", "2,0,0,11"]
			tempString        = tempArray[1];			// "2,0,0,11"
			versionArray      = tempString.split(",");	// ['2', '0', '0', '11']
		} else {
			versionArray      = versionStr.split(".");
		}
		var versionMajor      = versionArray[0];
		var versionMinor      = versionArray[1];
		var versionRevision   = versionArray[2];

        	// is the major.revision >= requested major.revision AND the minor version >= requested minor
		if (versionMajor > parseFloat(reqMajorVer)) {
			return true;
		} else if (versionMajor == parseFloat(reqMajorVer)) {
			if (versionMinor > parseFloat(reqMinorVer))
				return true;
			else if (versionMinor == parseFloat(reqMinorVer)) {
				if (versionRevision >= parseFloat(reqRevision))
					return true;
			}
		}
		return false;
	}
}

function AC_AddExtension(src, ext)
{
  if (src.indexOf('?') != -1)
    return src.replace(/\?/, ext+'?'); 
  else
    return src + ext;
}

function AC_Generateobj(objAttrs, params, embedAttrs) 
{ 
  var str = '';
  if (isIE && isWin && !isOpera)
  {
    str += '<object ';
    for (var i in objAttrs)
    {
      str += i + '="' + objAttrs[i] + '" ';
    }
    str += '>';
    for (var i in params)
    {
      str += '<param name="' + i + '" value="' + params[i] + '" /> ';
    }
    str += '</object>';
  }
  else
  {
    str += '<embed ';
    for (var i in embedAttrs)
    {
      str += i + '="' + embedAttrs[i] + '" ';
    }
    str += '> </embed>';
  }

  document.write(str);
}

function AC_FL_RunContent(){
  var ret = 
    AC_GetArgs
    (  arguments, ".swf", "movie", "clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"
     , "application/x-shockwave-flash"
    );
  AC_Generateobj(ret.objAttrs, ret.params, ret.embedAttrs);
}

function AC_SW_RunContent(){
  var ret = 
    AC_GetArgs
    (  arguments, ".dcr", "src", "clsid:166B1BCA-3F9C-11CF-8075-444553540000"
     , null
    );
  AC_Generateobj(ret.objAttrs, ret.params, ret.embedAttrs);
}

function AC_GetArgs(args, ext, srcParamName, classid, mimeType){
  var ret = new Object();
  ret.embedAttrs = new Object();
  ret.params = new Object();
  ret.objAttrs = new Object();
  for (var i=0; i < args.length; i=i+2){
    var currArg = args[i].toLowerCase();    

    switch (currArg){	
      case "classid":
        break;
      case "pluginspage":
        ret.embedAttrs[args[i]] = args[i+1];
        break;
      case "src":
      case "movie":	
        args[i+1] = AC_AddExtension(args[i+1], ext);
        ret.embedAttrs["src"] = args[i+1];
        ret.params[srcParamName] = args[i+1];
        break;
      case "onafterupdate":
      case "onbeforeupdate":
      case "onblur":
      case "oncellchange":
      case "onclick":
      case "ondblclick":
      case "ondrag":
      case "ondragend":
      case "ondragenter":
      case "ondragleave":
      case "ondragover":
      case "ondrop":
      case "onfinish":
      case "onfocus":
      case "onhelp":
      case "onmousedown":
      case "onmouseup":
      case "onmouseover":
      case "onmousemove":
      case "onmouseout":
      case "onkeypress":
      case "onkeydown":
      case "onkeyup":
      case "onload":
      case "onlosecapture":
      case "onpropertychange":
      case "onreadystatechange":
      case "onrowsdelete":
      case "onrowenter":
      case "onrowexit":
      case "onrowsinserted":
      case "onstart":
      case "onscroll":
      case "onbeforeeditfocus":
      case "onactivate":
      case "onbeforedeactivate":
      case "ondeactivate":
      case "type":
      case "codebase":
      case "id":
        ret.objAttrs[args[i]] = args[i+1];
        break;
      case "width":
      case "height":
      case "align":
      case "vspace": 
      case "hspace":
      case "class":
      case "title":
      case "accesskey":
      case "name":
      case "tabindex":
        ret.embedAttrs[args[i]] = ret.objAttrs[args[i]] = args[i+1];
        break;
      default:
        ret.embedAttrs[args[i]] = ret.params[args[i]] = args[i+1];
    }
  }
  ret.objAttrs["classid"] = classid;
  if (mimeType) ret.embedAttrs["type"] = mimeType;
  return ret;
}




/**
* Lightbox
*
* This libary is used to create a lightbox in a web application.  This library
* requires the Prototype 1.6 library and Script.aculo.us core, effects, and dragdrop
* libraries.  To use, add a div containing the content to be displayed anywhere on 
* the page.  To create the lightbox, add the following code:
*
*	var test;
*	
*	Event.observe(window, 'load', function () {
*		test = new Lightbox('idOfMyDiv');
*	});
*	
*	Event.observe('lightboxLink', 'click', function () {
*		test.open();
*	});
*
*	Event.observe('closeLink', 'click', function () {
*		test.close();
*	});
*     
*/

var Lightbox = Class.create({
	open : function () {
		this._centerWindow(this.container);
		this._fade('open', this.container);
	},
	
	close : function () {
		this._fade('close', this.container);
	},
	
	_fade : function fadeBg(userAction,whichDiv){
		if(userAction=='close'){
			new Effect.Opacity('bg_fade',
					   {duration:.5,
					    from:0.5,
					    to:0,
					    afterFinish:this._makeInvisible,
					    afterUpdate:this._hideLayer(whichDiv)});
		}else{
			new Effect.Opacity('bg_fade',
					   {duration:.5,
					    from:0,
					    to:0.5,
					    beforeUpdate:this._makeVisible,
					    afterFinish:this._showLayer(whichDiv)});
		}
	},
	
	_makeVisible : function makeVisible(){
		$("bg_fade").style.visibility="visible";
	},

	_makeInvisible : function makeInvisible(){
		$("bg_fade").style.visibility="hidden";
	},

	_showLayer : function showLayer(userAction){
		$(userAction).style.display="block";
	},
	
	_hideLayer : function hideLayer(userAction){
		$(userAction).style.display="none";
	},
	
	_centerWindow : function centerWindow(element) {
		var windowHeight = parseFloat($(element).getHeight())/2; 
		var windowWidth = parseFloat($(element).getWidth())/2;

		if(typeof window.innerHeight != 'undefined') {
			$(element).style.top = Math.round(document.body.offsetTop + ((window.innerHeight - $(element).getHeight()))/2)+'px';
			$(element).style.left = Math.round(document.body.offsetLeft + ((window.innerWidth - $(element).getWidth()))/2)+'px';
		} else {
			$(element).style.top = Math.round(document.body.offsetTop + ((document.documentElement.offsetHeight - $(element).getHeight()))/2)+'px';
			$(element).style.left = Math.round(document.body.offsetLeft + ((document.documentElement.offsetWidth - $(element).getWidth()))/2)+'px';
		}
	},
	
	initialize : function(containerDiv) {
		this.container = containerDiv;
		if($('bg_fade') == null) {
			var screen = new Element('div', {'id': 'bg_fade'});
			document.body.appendChild(screen);
		}
		new Draggable(this.container);
		this._hideLayer(this.container);
	}
});





// LiveValidation 1.3 (standalone version)
// Copyright (c) 2007-2008 Alec Hill (www.livevalidation.com)
// LiveValidation is licensed under the terms of the MIT License
var LiveValidation=function(B,A){this.initialize(B,A);};LiveValidation.VERSION="1.3 standalone";LiveValidation.TEXTAREA=1;LiveValidation.TEXT=2;LiveValidation.PASSWORD=3;LiveValidation.CHECKBOX=4;LiveValidation.SELECT=5;LiveValidation.FILE=6;LiveValidation.massValidate=function(C){var D=true;for(var B=0,A=C.length;B<A;++B){var E=C[B].validate();if(D){D=E;}}return D;};LiveValidation.prototype={validClass:"LV_valid",invalidClass:"LV_invalid",messageClass:"LV_validation_message",validFieldClass:"LV_valid_field",invalidFieldClass:"LV_invalid_field",initialize:function(D,C){var A=this;if(!D){throw new Error("LiveValidation::initialize - No element reference or element id has been provided!");}this.element=D.nodeName?D:document.getElementById(D);if(!this.element){throw new Error("LiveValidation::initialize - No element with reference or id of '"+D+"' exists!");}this.validations=[];this.elementType=this.getElementType();this.form=this.element.form;var B=C||{};this.validMessage=B.validMessage||"Ok";var E=B.insertAfterWhatNode||this.element;this.insertAfterWhatNode=E.nodeType?E:document.getElementById(E);this.onValid=B.onValid||function(){this.insertMessage(this.createMessageSpan());this.addFieldClass();};this.onInvalid=B.onInvalid||function(){this.insertMessage(this.createMessageSpan());this.addFieldClass();};this.onlyOnBlur=B.onlyOnBlur||false;this.wait=B.wait||0;this.onlyOnSubmit=B.onlyOnSubmit||false;if(this.form){this.formObj=LiveValidationForm.getInstance(this.form);this.formObj.addField(this);}this.oldOnFocus=this.element.onfocus||function(){};this.oldOnBlur=this.element.onblur||function(){};this.oldOnClick=this.element.onclick||function(){};this.oldOnChange=this.element.onchange||function(){};this.oldOnKeyup=this.element.onkeyup||function(){};this.element.onfocus=function(F){A.doOnFocus(F);return A.oldOnFocus.call(this,F);};if(!this.onlyOnSubmit){switch(this.elementType){case LiveValidation.CHECKBOX:this.element.onclick=function(F){A.validate();return A.oldOnClick.call(this,F);};case LiveValidation.SELECT:case LiveValidation.FILE:this.element.onchange=function(F){A.validate();return A.oldOnChange.call(this,F);};break;default:if(!this.onlyOnBlur){this.element.onkeyup=function(F){A.deferValidation();return A.oldOnKeyup.call(this,F);};}this.element.onblur=function(F){A.doOnBlur(F);return A.oldOnBlur.call(this,F);};}}},destroy:function(){if(this.formObj){this.formObj.removeField(this);this.formObj.destroy();}this.element.onfocus=this.oldOnFocus;if(!this.onlyOnSubmit){switch(this.elementType){case LiveValidation.CHECKBOX:this.element.onclick=this.oldOnClick;case LiveValidation.SELECT:case LiveValidation.FILE:this.element.onchange=this.oldOnChange;break;default:if(!this.onlyOnBlur){this.element.onkeyup=this.oldOnKeyup;}this.element.onblur=this.oldOnBlur;}}this.validations=[];this.removeMessageAndFieldClass();},add:function(A,B){this.validations.push({type:A,params:B||{}});return this;},remove:function(B,D){var E=false;for(var C=0,A=this.validations.length;C<A;C++){if(this.validations[C].type==B){if(this.validations[C].params==D){E=true;break;}}}if(E){this.validations.splice(C,1);}return this;},deferValidation:function(B){if(this.wait>=300){this.removeMessageAndFieldClass();}var A=this;if(this.timeout){clearTimeout(A.timeout);}this.timeout=setTimeout(function(){A.validate();},A.wait);},doOnBlur:function(A){this.focused=false;this.validate(A);},doOnFocus:function(A){this.focused=true;this.removeMessageAndFieldClass();},getElementType:function(){switch(true){case (this.element.nodeName.toUpperCase()=="TEXTAREA"):return LiveValidation.TEXTAREA;case (this.element.nodeName.toUpperCase()=="INPUT"&&this.element.type.toUpperCase()=="TEXT"):return LiveValidation.TEXT;case (this.element.nodeName.toUpperCase()=="INPUT"&&this.element.type.toUpperCase()=="PASSWORD"):return LiveValidation.PASSWORD;case (this.element.nodeName.toUpperCase()=="INPUT"&&this.element.type.toUpperCase()=="CHECKBOX"):return LiveValidation.CHECKBOX;case (this.element.nodeName.toUpperCase()=="INPUT"&&this.element.type.toUpperCase()=="FILE"):return LiveValidation.FILE;case (this.element.nodeName.toUpperCase()=="SELECT"):return LiveValidation.SELECT;case (this.element.nodeName.toUpperCase()=="INPUT"):throw new Error("LiveValidation::getElementType - Cannot use LiveValidation on an "+this.element.type+" input!");default:throw new Error("LiveValidation::getElementType - Element must be an input, select, or textarea!");}},doValidations:function(){this.validationFailed=false;for(var C=0,A=this.validations.length;C<A;++C){var B=this.validations[C];switch(B.type){case Validate.Presence:case Validate.Confirmation:case Validate.Acceptance:this.displayMessageWhenEmpty=true;this.validationFailed=!this.validateElement(B.type,B.params);break;default:this.validationFailed=!this.validateElement(B.type,B.params);break;}if(this.validationFailed){return false;}}this.message=this.validMessage;return true;},validateElement:function(A,C){var D=(this.elementType==LiveValidation.SELECT)?this.element.options[this.element.selectedIndex].value:this.element.value;if(A==Validate.Acceptance){if(this.elementType!=LiveValidation.CHECKBOX){throw new Error("LiveValidation::validateElement - Element to validate acceptance must be a checkbox!");}D=this.element.checked;}var E=true;try{A(D,C);}catch(B){if(B instanceof Validate.Error){if(D!==""||(D===""&&this.displayMessageWhenEmpty)){this.validationFailed=true;this.message=B.message;E=false;}}else{throw B;}}finally{return E;}},validate:function(){if(!this.element.disabled){var A=this.doValidations();if(A){this.onValid();return true;}else{this.onInvalid();return false;}}else{return true;}},enable:function(){this.element.disabled=false;return this;},disable:function(){this.element.disabled=true;this.removeMessageAndFieldClass();return this;},createMessageSpan:function(){var A=document.createElement("span");var B=document.createTextNode(this.message);A.appendChild(B);return A;},insertMessage:function(B){this.removeMessage();if((this.displayMessageWhenEmpty&&(this.elementType==LiveValidation.CHECKBOX||this.element.value==""))||this.element.value!=""){var A=this.validationFailed?this.invalidClass:this.validClass;B.className+=" "+this.messageClass+" "+A;if(this.insertAfterWhatNode.nextSibling){this.insertAfterWhatNode.parentNode.insertBefore(B,this.insertAfterWhatNode.nextSibling);}else{this.insertAfterWhatNode.parentNode.appendChild(B);}}},addFieldClass:function(){this.removeFieldClass();if(!this.validationFailed){if(this.displayMessageWhenEmpty||this.element.value!=""){if(this.element.className.indexOf(this.validFieldClass)==-1){this.element.className+=" "+this.validFieldClass;}}}else{if(this.element.className.indexOf(this.invalidFieldClass)==-1){this.element.className+=" "+this.invalidFieldClass;}}},removeMessage:function(){var A;var B=this.insertAfterWhatNode;while(B.nextSibling){if(B.nextSibling.nodeType===1){A=B.nextSibling;break;}B=B.nextSibling;}if(A&&A.className.indexOf(this.messageClass)!=-1){this.insertAfterWhatNode.parentNode.removeChild(A);}},removeFieldClass:function(){if(this.element.className.indexOf(this.invalidFieldClass)!=-1){this.element.className=this.element.className.split(this.invalidFieldClass).join("");}if(this.element.className.indexOf(this.validFieldClass)!=-1){this.element.className=this.element.className.split(this.validFieldClass).join(" ");}},removeMessageAndFieldClass:function(){this.removeMessage();this.removeFieldClass();}};var LiveValidationForm=function(A){this.initialize(A);};LiveValidationForm.instances={};LiveValidationForm.getInstance=function(A){var B=Math.random()*Math.random();if(!A.id){A.id="formId_"+B.toString().replace(/\./,"")+new Date().valueOf();}if(!LiveValidationForm.instances[A.id]){LiveValidationForm.instances[A.id]=new LiveValidationForm(A);}return LiveValidationForm.instances[A.id];};LiveValidationForm.prototype={initialize:function(B){this.name=B.id;this.element=B;this.fields=[];this.oldOnSubmit=this.element.onsubmit||function(){};var A=this;this.element.onsubmit=function(C){return(LiveValidation.massValidate(A.fields))?A.oldOnSubmit.call(this,C||window.event)!==false:false;};},addField:function(A){this.fields.push(A);},removeField:function(C){var D=[];for(var B=0,A=this.fields.length;B<A;B++){if(this.fields[B]!==C){D.push(this.fields[B]);}}this.fields=D;},destroy:function(A){if(this.fields.length!=0&&!A){return false;}this.element.onsubmit=this.oldOnSubmit;LiveValidationForm.instances[this.name]=null;return true;}};var Validate={Presence:function(B,C){var C=C||{};var A=C.failureMessage||"Can't be empty!";if(B===""||B===null||B===undefined){Validate.fail(A);}return true;},Numericality:function(J,E){var A=J;var J=Number(J);var E=E||{};var F=((E.minimum)||(E.minimum==0))?E.minimum:null;var C=((E.maximum)||(E.maximum==0))?E.maximum:null;var D=((E.is)||(E.is==0))?E.is:null;var G=E.notANumberMessage||"Must be a number!";var H=E.notAnIntegerMessage||"Must be an integer!";var I=E.wrongNumberMessage||"Must be "+D+"!";var B=E.tooLowMessage||"Must not be less than "+F+"!";var K=E.tooHighMessage||"Must not be more than "+C+"!";if(!isFinite(J)){Validate.fail(G);}if(E.onlyInteger&&(/\.0+$|\.$/.test(String(A))||J!=parseInt(J))){Validate.fail(H);}switch(true){case (D!==null):if(J!=Number(D)){Validate.fail(I);}break;case (F!==null&&C!==null):Validate.Numericality(J,{tooLowMessage:B,minimum:F});Validate.Numericality(J,{tooHighMessage:K,maximum:C});break;case (F!==null):if(J<Number(F)){Validate.fail(B);}break;case (C!==null):if(J>Number(C)){Validate.fail(K);}break;}return true;},Format:function(C,E){var C=String(C);var E=E||{};var A=E.failureMessage||"Not valid!";var B=E.pattern||/./;var D=E.negate||false;if(!D&&!B.test(C)){Validate.fail(A);}if(D&&B.test(C)){Validate.fail(A);}return true;},Email:function(B,C){var C=C||{};var A=C.failureMessage||"Must be a valid email address!";Validate.Format(B,{failureMessage:A,pattern:/^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i});return true;},Length:function(F,G){var F=String(F);var G=G||{};var E=((G.minimum)||(G.minimum==0))?G.minimum:null;var H=((G.maximum)||(G.maximum==0))?G.maximum:null;var C=((G.is)||(G.is==0))?G.is:null;var A=G.wrongLengthMessage||"Must be "+C+" characters long!";var B=G.tooShortMessage||"Must not be less than "+E+" characters long!";var D=G.tooLongMessage||"Must not be more than "+H+" characters long!";switch(true){case (C!==null):if(F.length!=Number(C)){Validate.fail(A);}break;case (E!==null&&H!==null):Validate.Length(F,{tooShortMessage:B,minimum:E});Validate.Length(F,{tooLongMessage:D,maximum:H});break;case (E!==null):if(F.length<Number(E)){Validate.fail(B);}break;case (H!==null):if(F.length>Number(H)){Validate.fail(D);}break;default:throw new Error("Validate::Length - Length(s) to validate against must be provided!");}return true;},Inclusion:function(H,F){var F=F||{};var K=F.failureMessage||"Must be included in the list!";var G=(F.caseSensitive===false)?false:true;if(F.allowNull&&H==null){return true;}if(!F.allowNull&&H==null){Validate.fail(K);}var D=F.within||[];if(!G){var A=[];for(var C=0,B=D.length;C<B;++C){var I=D[C];if(typeof I=="string"){I=I.toLowerCase();}A.push(I);}D=A;if(typeof H=="string"){H=H.toLowerCase();}}var J=false;for(var E=0,B=D.length;E<B;++E){if(D[E]==H){J=true;}if(F.partialMatch){if(H.indexOf(D[E])!=-1){J=true;}}}if((!F.negate&&!J)||(F.negate&&J)){Validate.fail(K);}return true;},Exclusion:function(A,B){var B=B||{};B.failureMessage=B.failureMessage||"Must not be included in the list!";B.negate=true;Validate.Inclusion(A,B);return true;},Confirmation:function(C,D){if(!D.match){throw new Error("Validate::Confirmation - Error validating confirmation: Id of element to match must be provided!");}var D=D||{};var B=D.failureMessage||"Does not match!";var A=D.match.nodeName?D.match:document.getElementById(D.match);if(!A){throw new Error("Validate::Confirmation - There is no reference with name of, or element with id of '"+D.match+"'!");}if(C!=A.value){Validate.fail(B);}return true;},Acceptance:function(B,C){var C=C||{};var A=C.failureMessage||"Must be accepted!";if(!B){Validate.fail(A);}return true;},Custom:function(D,E){var E=E||{};var B=E.against||function(){return true;};var A=E.args||{};var C=E.failureMessage||"Not valid!";if(!B(D,A)){Validate.fail(C);}return true;},now:function(A,D,C){if(!A){throw new Error("Validate::now - Validation function must be provided!");}var E=true;try{A(D,C||{});}catch(B){if(B instanceof Validate.Error){E=false;}else{throw B;}}finally{return E;}},fail:function(A){throw new Validate.Error(A);},Error:function(A){this.message=A;this.name="ValidationError";}};




/*
PHPLiveX, PHP / AJAX Library & Framework
Version 2.6, Released In 05.02.2010
Copyright (C) 2006-2010 Arda Beyazoglu
http://www.phplivex.com, arda@beyazoglu.com

This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 3 of the License, or any later version. See the GNU
Lesser General Public License for more details.
*/

// Creates the main configuration
function PHPLiveX(){
	this.Options = {	
		type: "asynchronous",
		mode: "rw",
		target: 'default_dummy_ajax_target',
		preloader: 'default_dummy_ajax_preloader',
		method: "post",
		onCreate: function(){},
		onUninitialized: function(){},
		onLoading: function(){},
		onRequest: function(){},
		onInteraction: function(){},
		onFinish: function(){}, 
		onUpdate: function(){},
		onFailure: function(){},
		onTimeout: function(){},
		onPreload: {"start": function(){}, "complete": function(){}},
		interval: 0,
		id: null,
		clear_content: true,
		preloader_style: "display",
		target_attr: "innerContent",
		url: "",
		eval_scripts: true,
		content_type: "text",
		headers: {},
		params: null,
		caching: false,
		history: false,
		timeout: 30000
	};
	
	this.Timeout = null;
	this.CallType = "internal";
	
	if(navigator.appName == "Opera") this.Browser = "opera";
	else if(navigator.appName == "Microsoft Internet Explorer") this.Browser = "ie";
	else this.Browser = "gecko";
	
	this.XML_HTTP = this.GetXmlHttp();
};

// Validates user defined parameters
PHPLiveX.prototype.HandleParams = function(user_options){
	var errors = [];
	
	for(param in user_options){
		if(this.Options[param] == undefined && typeof(this.Options[param]) != "object"){
			errors.push("* Undefined parameter: " + param);
			continue;
		}
		this.Options[param] = user_options[param];
	}
	
	if(typeof(this.Options.target) == "string"){
		if(document.getElementById(this.Options.target)){
			this.Options.target = document.getElementById(this.Options.target);
		}else{
			errors.push("* Target not found with id=" + this.Options.target  + "!");
			this.Options.preloader = null;
		}
		if(this.Options.target_attr == "innerContent"){
			if(this.Options.target.type == "select-one" || this.Options.target.type == "select-multiple") this.Options.target_attr = "options";
			else if(this.Options.target == "[object HTMLInputElement]" || this.Options.target.type != undefined) this.Options.target_attr = "value";
			else this.Options.target_attr = "innerHTML";
		}
	}

	if(typeof(this.Options.preloader) == "string"){
		if(document.getElementById(this.Options.preloader)){
			this.Options.preloader = document.getElementById(this.Options.preloader);
		}else{
			errors.push("* Preloader not found with id=" + this.Options.preloader  + "!");
			this.Options.preloader = null;
		}
	}
	
	if(this.Options.url == "") this.Options.url = window.location.href;
	
	if(errors.length > 0){
		var warning = errors.join("\r\n");
		alert("PHPLiveX Error:\r\n" + warning);
	}
};

// Converts an xml string to xmldoc
PHPLiveX.prototype.CreateXML = function(txt){
	if(this.Browser == "ie"){
		try{
			xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
			xmlDoc.async = false;
			xmlDoc.loadXML(txt);
			return xmlDoc; 
		}catch(e){}
	}else{
		try{
			parser = new DOMParser();
			xmlDoc = parser.parseFromString(txt, "text/xml");
			return xmlDoc;
		}catch(e){}
	}
	return false;
};

// Creates xmlhttp object
PHPLiveX.prototype.GetXmlHttp = function(){
	objXmlHttp = false;
	if(window.XMLHttpRequest){
		objXmlHttp = new XMLHttpRequest();
		if (objXmlHttp.overrideMimeType){
			objXmlHttp.overrideMimeType("text/xml");
		}
	}else if(window.ActiveXObject){
		try{
			objXmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
		}catch(e){
			try{ objXmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); }
			catch(e){}
		}
	}

	if (!objXmlHttp) {
		alert("Cannot create an XMLHTTP instance");
		return false;
	}

	return objXmlHttp;
};

// Initializes preloading
PHPLiveX.prototype.CreatePreloading = function(){
	if(this.Options.preloader != null){
		if(this.Options.preloader_style == "display") this.Options.preloader.style.display = "block";
		this.Options.preloader.style.visibility = "visible";
	}
	this.Options.onPreload.start();
	if(this.Options.clear_content) eval("this.Options.target." + this.Options.target_attr + " = '';");
};

// Ends preloading
PHPLiveX.prototype.CompletePreloading = function(){
	if(this.Options.preloader != null){
		if(this.Options.preloader_style == "display") this.Options.preloader.style.display = "none";
		this.Options.preloader.style.visibility = "hidden";
	}
	this.Options.onPreload.complete();
};

PHPLiveX.prototype.HandleResponse = function(response){
	if(this.Options.content_type == "json" && response != "") eval("response = " + response + ";");
	else if(this.Options.content_type == "xml" && response != "") response = this.CreateXML(response);
	
	if(this.Options.content_type == "text"){
		if(this.Options.eval_scripts) response = PLX.EvalScripts(response);
		response = PLX.EvalStyles(response);
		
		var test_integer = /^[\+\-]?\d*$/;
		if(response != "" && test_integer.test(response)) response = parseInt(response);
	}
	
	var go = this.Options.onFinish(response, this);
	
	if(this.Options.target != null && this.Options.content_type != "xml" && go != false){
		var item = this.Options.target;
		if((item.type == "select-one" || item.type == "select-multiple") &&  this.Options.target_attr == "options"){
			if(this.Options.mode == "rw"){
				lng = item.options.length;
				for(k=0; k<lng; k++) item.remove(0);
			}
			
			for(var i=0; i<response.length; i++){
				option = response[i];
				var opt = document.createElement("option");
				for(key in option){
					val = option[key];
					eval("opt." + key + " = val;");
				}
				
				if(this.Options.mode == "aw" || this.Options.mode == "rw"){
					if(this.Browser == "ie") item.add(opt);
					else item.add(opt, null);
				}else if(options.mode == "asw"){
					if(this.Browser == "ie") item.add(opt, 0);
					else item.add(opt, item.options[0]);
				}
			}
		}else{
			switch(this.Options.mode){
				case "aw": eval("item." +  this.Options.target_attr + " += response;"); break;
				case "rw": eval("item." +  this.Options.target_attr + " = response;"); break;
				case "asw": eval("item." +  this.Options.target_attr + " = response + item." +  this.Options.target_attr + ";"); break;
			}
		}
	}

	if(go != false) this.Options.onUpdate(response, this);
	this.CompletePreloading();
	
	if(this.Options.history && window.dhtmlHistory){
		this.AddToHistory();
	}
};

// Initiliazes the ajax request and handle the response
PHPLiveX.prototype.UtilizeResponse = function(funcName, funcArgs, funcUrl){
	if(typeof(funcName) == "object"){
		if(funcName.cls) funcName = funcName.cls + "::" + funcName.method;
		else if(funcName.obj) funcName = funcName.obj + "->" + funcName.method;
	}
	var data = (funcName) ? "plxf=" + escape(funcName) : "";
	var args = new Array();
	
	if(funcArgs.length > 0){
		if(funcName){
			for (i=0;i<funcArgs.length;i++) data += "&plxa[]=" + PLX.UTF8_Encode(funcArgs[i]);
		}else{
			for (i=0;i<funcArgs.length;i++){
				key = PLX.UTF8_Encode(funcArgs[i].split("~=~")[0]);
				val = PLX.UTF8_Encode(funcArgs[i].split("~=~")[1]);
				data += "&" + key + "=" + val;
			}
			data = data.substring(1);
		}
	}
	
	var asynchronous = (this.Options.type == "asynchronous") ? true : false;

	if(funcUrl.match("#")) funcUrl = funcUrl.split("#")[0];
	if(this.Options.method.toUpperCase() == "GET"){
		if(!this.Options.caching) data += "&RequestId=" + new Date().getTime();
		if(funcUrl.indexOf("?") != -1){
			data = (funcUrl.indexOf("&")) ? "&" + data : data;
			this.XML_HTTP.open("GET", funcUrl + "&" + data, asynchronous);
		}else{
			this.XML_HTTP.open("GET", funcUrl + "?" + data, asynchronous);
		}
	}else{
		this.XML_HTTP.open("POST", funcUrl, asynchronous);
	}
	
	if(this.Options.method.toUpperCase() == "POST"){
		this.XML_HTTP.setRequestHeader("Method", "POST " + funcUrl + " HTTP/1.1");
		this.XML_HTTP.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		this.XML_HTTP.setRequestHeader("Accept", "text/javascript, text/html, text/xml, application/xml, application/json, */*");
	}
	
	for(key in this.Options.headers){
		if(key == "toJSONString") continue;
		this.XML_HTTP.setRequestHeader(key, this.Options.headers[key]);
	}

	if(asynchronous){
		this.CreatePreloading();
		this.Options.onCreate(this.XML_HTTP);
		var _root = this;
		
		this.XML_HTTP.onreadystatechange = function(){
			if(this.readyState == 0){
				_root.Options.onUninitialized(_root);
			}else if(this.readyState == 1){
				_root.Options.onLoading(_root);
			}else if(this.readyState == 2){
				_root.Options.onRequest(_root);
			}else if(this.readyState == 3){
				_root.Options.onInteraction(_root);
			}else if(this.readyState == 4){
				clearTimeout(_root.Timeout);
				
				var response = this.responseText;
				if(_root.CallType == "internal"){
					if(response.indexOf("<phplivex>") != -1){
						var parts = response.split("<phplivex>");
						response = parts[parts.length-1].split("</phplivex>")[0];
					}else{
						response = "";
					}
				}
				
				_root.HandleResponse(response);
			}
		};
		
		(this.Options.method.toUpperCase() == "GET") ? this.XML_HTTP.send(null) : this.XML_HTTP.send(data);
		this.Timeout = setTimeout(function(){
			_root.XML_HTTP.abort();
			_root.Options.onTimeout();
			},
			this.Options.timeout
		);
		
	}else{
		(this.Options.method.toUpperCase() == "GET") ? this.XML_HTTP.send(null) : this.XML_HTTP.send(data);

		var response = this.XML_HTTP.responseText;
		if(response.indexOf("<phplivex>") != -1){
			var parts = response.split("<phplivex>");
			response = parts[parts.length-1].split("</phplivex>")[0];
		}

		if(this.Options.eval_scripts) response = PLX.EvalScripts(response);
		response = PLX.EvalStyles(response);
		
		var test_integer = /^[\+\-]?\d*$/;
		if(response != "" && test_integer.test(response)) response = parseInt(response);
		
		if(_root.Options.content_type == "json" && response != "") eval("response = " + response + ";");
		if(_root.Options.content_type == "xml" && response != "") response = _root.CreateXML(response);
		
		return response;
	}
};

// Client side callback for ajax requests
PHPLiveX.prototype.Callback = function(funcName, funcArgs){
	var params, realArgs = funcArgs;
	if(funcArgs.length != undefined){
		params = funcArgs[funcArgs.length - 1];
		if(!params.id) params.id = PLX.RandomString();
		realArgs[realArgs.length - 1] = params;
	}else{
		if(!funcArgs.id) realArgs.id = PLX.RandomString();
		params = realArgs;
	}
	this.HandleParams(params);
	
	if(this.Options.params && !funcName){
		var newArgs = [];
		for(pairKey in this.Options.params){
			value = this.Options.params[pairKey];
			if(typeof(value) == "object") value = PLX.Json2String(value);
			newArgs.push(pairKey + "~=~" + value);
		}
		funcArgs = newArgs.concat(funcArgs);
	}
	
	if(this.Options.history && window.dhtmlHistory) this.CreateMainHistory();
	
	var args = [];
	for(i=0;i<funcArgs.length-1;i++){
		if(typeof(funcArgs[i]) == "object"){
			args.push("<plxobj>" + PLX.Json2String(funcArgs[i]) + "</plxobj>");
		}else if(typeof(funcArgs[i]) == "boolean"){
			if(funcArgs[i] == false) args.push(0);
			else args.push(1);
		}else{
			if(String(funcArgs[i]).indexOf("+")) args.push(String(funcArgs[i]).replace("+", encodeURIComponent("+"), "g"));
			else args.push(funcArgs[i]);
		}
	}
	
	try{
		if(this.Options.type == "synchronous") return this.UtilizeResponse(funcName, args, this.Options.url);
		else this.UtilizeResponse(funcName, args, this.Options.url);
	}catch(ex){
		this.Options.onFailure(ex);
		return;
	};
	
	if(this.Options.interval > 0 && !PLX.Intervals[this.Options.id] && funcName){
		var initialArgs = []; // To convert js array to json array
		for(i=0; i<realArgs.length; i++) initialArgs[i] = realArgs[i];
		initialArgs = PLX.Json2String(initialArgs);
		
		if(typeof(funcName) == "object") funcName = PLX.Json2String(funcName);
		else if(typeof(funcName) == "string") funcName = "'" + funcName + "'";
		
		PLX.Intervals[this.Options.id] = setInterval("new PHPLiveX().Callback(" + funcName + ", " + initialArgs + ");", this.Options.interval);
	}
	return;
};

// Sends ajax request to an url
PHPLiveX.prototype.ExternalRequest = function(options){
	this.CallType = "external";
	
	if(!options.id) options.id = PLX.RandomString();
	var r = this.Callback(false, options);
	if(this.Options.interval > 0 && !PLX.Intervals[this.Options.id]){
		PLX.Intervals[this.Options.id] = setInterval("new PHPLiveX().Callback(false, " + PLX.Json2String(options) + ");", this.Options.interval);
	}
	return r;
};

// Submits an html form via ajax
PHPLiveX.prototype.SubmitForm = function(form, options){
	this.CallType = "external";
	
	if(typeof(form) == "string") form = document.getElementById(form) || document.forms[form];
	if(!form.id) form.id = PLX.RandomString();
	
	if(options == null) options = {};
	if(!options.id) options.id = PLX.RandomString();
	
	if(!options.url && form.action != ""){
		options.url = form.action;
	}else if(!options.url && form.action == ""){
		alert("Please define an action for form");
		return false;
	}
	
	if(!options.method){
		options.method = (form.method != "") ? form.method : "post";
	}
	
	var file_upload = false;
	var args = [];
	var fields = form.elements;
	for(i=0; i<fields.length; i++){
		if(fields[i].name == "" || fields[i].type == "submit" || fields[i].type == "button" || fields[i].type == "reset") continue;
		if((fields[i].type == "checkbox" || fields[i].type == "radio") && !fields[i].checked) continue;
		
		if(fields[i].type == "file"){
			file_upload = true;
			break;
		}else if(fields[i].type == "select-multiple"){
			opts = fields[i].options;
			lim = opts.length;
			for(k=0; k<lim; k++){
				if(opts[k].selected) args.push(fields[i].name + "~=~" + opts[k].text);
			}
		}else{
			args.push(fields[i].name + "~=~" + fields[i].value);
		}
	}
	
	if(file_upload){
		this.HandleParams(options);
		this.CreatePreloading();
		
		var iframe = document.getElementById("plx_iframe_" + form.id);
		if(!iframe){
			PLX.FormIframes[form.id] = this;
			var iframe = "<iframe onload=\"PLX.FormIframeLoaded(this, '" + form.id + "')\" id=\"plx_iframe_" + form.id + "\" name=\"plx_iframe_" + form.id + "\" style=\"border:0px;padding:0px;margin:0px;width:0px;height:0px;\"></iframe>";
			var div = document.createElement("div");
			div.setAttribute((this.Browser == "ie") ? "cssText" : "style", "border:0px;padding:0px;margin:0px;width:0px;height:0px;visibility:hidden;position:absolute;");
			div.innerHTML = iframe;
			document.body.appendChild(div);
			
			form.method = "post";
			form.target = "plx_iframe_" + form.id;
		}
		
		return true;
	}else{
		args.push(options);
		this.Callback(false, args);
		
		if(this.Options.interval > 0 && !PLX.Intervals[this.Options.id]){
			PLX.Intervals[this.Options.id] = setInterval("new PHPLiveX().SubmitForm('" + form.id + "', " + PLX.Json2String(options) + ");", this.Options.interval);
		}
		
		return false;
	}
};

// A shorthand for PHPLiveX class in some cases and contains some helper methods
var PLX = {	
	// Converts from json to string
	Json2String: function(obj){
		var type = (obj.length == undefined) ? "object" : "array";
		var values = [];
		for(key in obj){
			if(key == "toJSONString") continue;
			if(typeof(obj[key]) == "string"){
				if(type == "object") val = "\"" + key + "\": " + "\"" + obj[key] + "\"";
				else val = "\"" + obj[key] + "\"";
			}else if(typeof(obj[key]) == "object" && obj[key] != null){
				if(type == "object") val = "\"" + key + "\": " + PLX.Json2String(obj[key]);
				else val = PLX.Json2String(obj[key]);
			}else if(typeof(obj[key]) == undefined || obj[key] == null){
				if(type == "object") val = "\"" + key + "\": " + null;
				else val = null;
			}else{
				if(type == "object") val = "\"" + key + "\": " + obj[key];
				else val = obj[key];
			}
			values.push(val);
		}
		
		values = values.join(",");
		return (type == "object") ? "{" + values + "}" : "[" + values + "]";
	},
	
	// Array equivalent of indexOf method
	InArray: function(value, arr){
        for (i=0; i<arr.length; i++){
            if(arr[i] === value) return true;
        }
        return false;
    },
    
    // Copies a json object to another
    JoinObjects: function(obj1, obj2){
		var joint = obj1;
    	if(typeof(obj1) == "object" && typeof(obj2) == "object"){
			for(var key in obj2) joint[key] = obj2[key];
		}
		return joint;
    },
	
	// Returns a random code
	RandomString: function(len){
		if(len == null) len = 6;
		var chars = "ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
		var code = "";
		for (i=0; i<len; i++) {
			var rnum = Math.floor(Math.random() * chars.length);
			code += chars.substring(rnum, rnum + 1);
		}
		return code;
	},
	
	// Encodes the text as utf8
	UTF8_Encode: function(text){
		if(typeof(text) != "string") return escape(text);
		text = text.replace(/\r\n/g,"\n");
		var utftext = "";
		for (var n = 0; n < text.length; n++){
			var c = text.charCodeAt(n);
			if (c < 128) {
				utftext += String.fromCharCode(c);
			}else if((c > 127) && (c < 2048)){
				utftext += String.fromCharCode((c >> 6) | 192);
				utftext += String.fromCharCode((c & 63) | 128);
			}else{
				utftext += String.fromCharCode((c >> 12) | 224);
				utftext += String.fromCharCode(((c >> 6) & 63) | 128);
				utftext += String.fromCharCode((c & 63) | 128);
			}
		}
		return escape(utftext);
	},
	
	// Searchs for javascript codes in the text and appends them to the page
	EvalScripts: function(text){
		var jscode = "";
		var jsparts = text.match(/<script[^>]*>(.|\n|\t|\r)*?<\/script>/gi);
		if(jsparts){
			lng = jsparts.length;
			for(i=0;i<lng;i++){
				jscode += jsparts[i].replace(/<script[^>]*>|<\/script>/gi, "");
				text = text.replace(jsparts[i], "");
			}
			var script = document.createElement("script");
			script.type = "text/javascript";
			script.lang = "javascript";
			script.text = jscode;
			document.getElementsByTagName("head")[0].appendChild(script);
		}
		
		return text;
	},
	
	// Searchs for css codes in the text and appends them to the page
	EvalStyles: function(text){
		var styles = text.match(/<style[^>]*>(.|\n|\t|\r)*?<\/style>/gi);
		if(styles){
			var csscode = "";
			lng = styles.length;
			for(i=0;i<lng;i++){
				csscode += styles[i].replace(/<style[^>]*>|<\/style>/gi, "");
				text = text.replace(styles[i], "");
			}
			var stl = document.createElement("style");
			stl.type = "text/css";
			if(this.Browser == "ie") stl.styleSheet.cssText = csscode;
			else stl.innerHTML = csscode;
			document.getElementsByTagName("head")[0].appendChild(stl);
		}
		
		return text;
	},
	
	// Shorthand for PHPLiveX::ExternalRequest. Sends an ajax request to an url
	Request: function(options){
		new PHPLiveX().ExternalRequest(options);
	},
	
	// Shorthand for PHPLiveX::SubmitForm. Submits a form via ajax
	Submit: function(frm, options){
		return new PHPLiveX().SubmitForm(frm, options);
	},
	
	// Loads a javascript file to the page
	LoadJS: function(path, options){
		if(!options) options = {};
		var onFinish = (options.onFinish) ? options.onFinish : function(){};
		var params = PLX.JoinObjects(options, {
			url: path,
			onFinish: function(response){
				PLX.EvalScripts("<script type='text/javascript'>" + response + "</script>");
				onFinish(response);
			}
		});
	},
	
	// Loads a css file to the page
	LoadCSS: function(path, options){
		if(!options) options = {};
		var onFinish = (options.onFinish) ? options.onFinish : function(){};
		var params = PLX.JoinObjects(options, {
			url: path,
			onFinish: function(response){
				PLX.EvalStyles("<style type='text/css'>" + response + "</style>");
				onFinish(response);
			}
		});
		PLX.Request(params);
	},
	
	// Timeout variables used for repeated requests
	Intervals: {},
	
	// Clear the timeout and stop the request repetition
	Stop: function(id){
		if(PLX.Intervals[id] != undefined) clearInterval(PLX.Intervals[id]);
	},
	
	// Registered file uploads
	Uploads: {},
	
	// Error codes for file uploads
	SIZE_ERROR: "SIZE_ERROR",
	TYPE_ERROR: "TYPE_ERROR",
	TEMP_FILE_ERROR: "TEMP_FILE_ERROR",
	
	// Starts ajax file upload
	InitializeUpload: function(id){
		var value = PLX.Uploads[id].el.value.split(".");
		var ftype = value[value.length - 1];
		if((PLX.Uploads[id].allowed_types.length > 0 && !PLX.InArray(ftype, PLX.Uploads[id].allowed_types)) || PLX.InArray(ftype, PLX.Uploads[id].disallowed_types)){
			PLX.Uploads[id].onError(PLX.TYPE_ERROR);
			return;
		}
		
		document.getElementById("plx_form_" + PLX.Uploads[id].uid).submit();
		if(!PLX.Uploads[id].click_el) PLX.Uploads[id].el.disabled = true;
		
		PLX.Uploads[id].BeginUpload = function(){
			PLX.ProgressUpload(id, PLX.Uploads[id].uid, PLX.Uploads[id].tmp_dir, {
				id: PLX.Uploads[id].uid,
				interval: PLX.Uploads[id].interval,
				content_type: "json",
				onFinish: function(response, root){
					var id = response.id;
					if(response.error){
						PLX.StopUpload(id);
						PLX.Uploads[id].onError(response.error);
						return;
					}
					
					if(PLX.Uploads[id].uploaded.length == 2) PLX.Uploads[id].uploaded.shift();
					PLX.Uploads[id].uploaded.push(response.uploaded);
					var bytes_appended = PLX.Uploads[id].uploaded[1] - PLX.Uploads[id].uploaded[0];
					var speed = parseFloat(bytes_appended / (PLX.Uploads[id].interval / 1000));
					
					var progress = {
						total: response.total,
						uploaded: response.uploaded,
						percent: response.percent,
						speed: speed,
						id: id,
						completed: false
					};
					
					if(response.percent == 100){
						PLX.StopUpload(id);
						progress = PLX.JoinObjects(progress, {completed:true, file_tmp_name:response.file_tmp_name, file_name:response.file_name});
					}
					
					PLX.Uploads[id].onProgress(progress);
				}
			});
		};
		setTimeout("PLX.Uploads['" + id + "'].BeginUpload();", PLX.Uploads[id].interval);
	},
	
	// Callback for PHPLiveX::ProgressUpload method tracking the upload progress
	ProgressUpload: function(id, options){
		return new PHPLiveX().Callback({instance:"PLX", cls:"PHPLiveX", method:"ProgressUpload"}, PLX.ProgressUpload.arguments);
	},
	
	// Stops the upload process with specified id
	StopUpload: function(id){
		PLX.Stop(PLX.Uploads[id].uid);
		if(!PLX.Uploads[id].click_el) PLX.Uploads[id].el.disabled = false;
	},
	
	// Adjusts the elements for ajax upload
	AjaxifyUpload: function(elements, cfg){
		var config = {
			cgi_path: "upload.cgi", // the upload cgi script path (upload.cgi)
			tmp_dir: "tmp", // a temporary directory for upload operations (relative to upload.cgi)
			onProgress: function(){}, // a custom function to generate progress bars, upload speed etc. and upload the files
			onError: function(){}, // a custom function to handle possible errors
			interval: 2000, // a interval in milliseconds to control the upload process
			insensitivity: 0.10, // a sleep interval in seconds to read bytes in order !IMPORTANT
			max_size: 5242880, // allowed max file size
			allowed_types: [], // allowed file types
			disallowed_types: [], // disallowed file types
			click_el: false // true to use another element like button to begin upload. By default, it starts just after selecting a file
		};
		config = PLX.JoinObjects(config, cfg);
		
		if(typeof(elements) == "string" || (typeof(elements) == "object" && elements.length == undefined)) elements = [elements];
		for(var i=0; i<elements.length; i++){
			var el = (typeof(elements[i]) == "string") ? document.getElementById(elements[i]) : elements[i];
			var uid = new Date().getTime() + PLX.RandomString();
			PLX.Uploads[el.id] = PLX.JoinObjects({uploaded:[0], el:el, uid:uid}, config);
			
			try{
				var frm = document.createElement("<form enctype=\"multipart/form-data\">");
				var iframe = document.createElement("<iframe name=\"plx_iframe_" + uid + "\">");
			}catch(ex){
				var frm = document.createElement("form");
				frm.enctype = "multipart/form-data";
				var iframe = document.createElement("iframe");
				iframe.name = "plx_iframe_" + uid;
			};
			
			frm.id = "plx_form_" + uid;
			frm.name = frm.id;
			frm.style.background = "none";
			frm.style.padding = "0px";
			frm.style.margin = "0px";
			frm.style.border = "0px";
			frm.method = "POST";
			frm.target = "plx_iframe_" + uid;
			frm.action = config.cgi_path + "?uid=" + uid + "&max_size=" + config.max_size + "&insensitivity=" + config.insensitivity;
			
			iframe.style.border = "0px";
			iframe.style.padding = "0px";
			iframe.style.margin = "0px";
			iframe.style.visibility = "hidden";
			iframe.style.position = "absolute";
			iframe.style.height = "0px";
			iframe.style.width = "0px";
			
			el.parentNode.insertBefore(frm, el);
			frm.appendChild(el);
			frm.parentNode.insertBefore(iframe, frm.nextSibling);
			
			if(config.click_el) continue;
			el.onchange = function(){
				if(this.value == "") return;
				PLX.InitializeUpload(this.id);
			};
		}
	},
	
	// PHPLiveX object for each form including file upload
	FormIframes: {},
	
	// Get form response
	FormIframeLoaded: function(iframe, form_id){
		var response = iframe.contentWindow.document.body.innerHTML;
		PLX.FormIframes[form_id].HandleResponse(response, PLX.FormIframes[form_id]);
	}
};



/**
 * reflex.js 1.21 (21-Mar-2009)
 * (c) by Christian Effenberger 
 * All Rights Reserved
 * Source: reflex.netzgesta.de
 * Distributed under Netzgestade Software License Agreement
 * http://www.netzgesta.de/cvi/LICENSE.txt
 * License permits free of charge
 * use on non-commercial and 
 * private web sites only 
**/

var tmp = navigator.appName == 'Microsoft Internet Explorer' && navigator.userAgent.indexOf('Opera') < 1 ? 1 : 0;
if(tmp) var isIE = document.namespaces ? 1 : 0;

if(isIE) {
	if(document.namespaces['v']==null) {
		var e=["shape","shapetype","group","background","path","formulas","handles","fill","stroke","shadow","textbox","textpath","imagedata","line","polyline","curve","roundrect","oval","rect","arc","image"],s=document.createStyleSheet(); 
		for(var i=0; i<e.length; i++) {s.addRule("v\\:"+e[i],"behavior: url(#default#VML);");} document.namespaces.add("v","urn:schemas-microsoft-com:vml");
	} 
}

function getImages(className){
	var children = document.getElementsByTagName('img'); 
	var elements = new Array(); var i = 0;
	var child; var classNames; var j = 0;
	for (i=0;i<children.length;i++) {
		child = children[i];
		classNames = child.className.split(' ');
		for (var j = 0; j < classNames.length; j++) {
			if (classNames[j] == className) {
				elements.push(child);
				break;
			}
		}
	}
	return elements;
}

function getClasses(classes,string){
	var temp = '';
	for (var j=0;j<classes.length;j++) {
		if (classes[j] != string) {
			if (temp) {
				temp += ' '
			}
			temp += classes[j];
		}
	}
	return temp;
}

function getClassValue(classes,string){
	var temp = 0; var pos = string.length;
	for (var j=0;j<classes.length;j++) {
		if (classes[j].indexOf(string) == 0) {
			temp = Math.min(classes[j].substring(pos),100);
			break;
		}
	}
	return Math.max(0,temp);
}
function getClassColor(classes,string){
	var temp = 0; var str = ''; var pos = string.length;
	for (var j=0;j<classes.length;j++) {
		if (classes[j].indexOf(string) == 0) {
			temp = classes[j].substring(pos);
			str = '#' + temp.toLowerCase();
			break;
		}
	}
	if(str.match(/^#[0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f]$/i)) {return str; }else {return 0;}
}
function getClassAttribute(classes,string){
	var temp = 0; var pos = string.length;
	for (var j=0;j<classes.length;j++) {
		if (classes[j].indexOf(string) == 0) {
			temp = 1; 
			break;
		}
	}
	return temp;
}

function clipPolyRight(ctx,x,y,w,h,t,d,s) {
	var z = (h-t-t)/h;
	ctx.beginPath(); 
	ctx.moveTo(x,y); ctx.lineTo(w,y+t); ctx.lineTo(w,y+h-t); ctx.lineTo(x,y+h);
	if(d>0) {ctx.lineTo(x,y+h-s); ctx.lineTo(w,y+h-t-(z*s)); ctx.lineTo(w,y+h-t-(z*(s+d))); ctx.lineTo(x,y+h-s-d);}
	ctx.closePath();
}	

function clipPolyLeft(ctx,x,y,w,h,t,d,s) {
	var z = (h-t-t)/h;
	ctx.beginPath(); 
	ctx.moveTo(x,y+t); ctx.lineTo(w,y+1); ctx.lineTo(w,y+h); ctx.lineTo(x,y+h-t);
	if(d>0) {ctx.lineTo(x,y+h-t-(z*s)); ctx.lineTo(w,y+h-s); ctx.lineTo(w,y+h-s-d); ctx.lineTo(x,y+h-t-(z*(s+d))); }
	ctx.closePath();
}
	
function strokePolyRight(ctx,x,y,w,h,t,d,s,b) {
	var z = (h-t-t)/h; var n = (b>=1?1:0);
	ctx.beginPath(); 
	ctx.moveTo(x+b,y+b); ctx.lineTo(w-b,y+t+b-n); ctx.lineTo(w-b,y+h-t-(z*(s+d))-b); ctx.lineTo(x+b,y+h-s-d-b);
	ctx.closePath();
}
function strokePolyLeft(ctx,x,y,w,h,t,d,s,b) {
	var z = (h-t-t)/h; var n = (b>=1?1:0);
	ctx.beginPath(); 
	ctx.moveTo(x+b,y+t+b-n); ctx.lineTo(w-b,y+b); ctx.lineTo(w-b,y+h-s-d-b); ctx.lineTo(x+b,y+h-t-(z*(s+d))-b);
	ctx.closePath();
}

function clipReflex(ctx,x,y,w,h,t,d,s,o) {
	var z = (h-t-t)/h;
	ctx.beginPath();
	if(o=='r') {
		ctx.moveTo(x,y+h-s); ctx.lineTo(w,y+h-t-(z*s)); ctx.lineTo(w,y+h-t+2); ctx.lineTo(x,y+h+2);
	}else {
		ctx.moveTo(w,y+h+2); ctx.lineTo(w,y+h-s); ctx.lineTo(x,y+h-t-(z*s)); ctx.lineTo(x,y+h-t+2); 
	}
	ctx.closePath();
}

function clearReflex(ctx,x,y,w,h,t,d,s,o) {
	var z = (h-t-t)/h;
	ctx.beginPath();
	if(o=='r') {
		ctx.moveTo(x,y+h-1); ctx.lineTo(w,y+h-t-1); ctx.lineTo(w,y+h-t+1); ctx.lineTo(x,y+h+1);
	}else {
		ctx.moveTo(w,y+h-1); ctx.lineTo(x,y+h-t-1); ctx.lineTo(x,y+h-t+1); ctx.lineTo(w,y+h+1);
	}
	ctx.closePath();
}

function addIEReflex() {
	var theimages = getImages('reflex');
	var image, object, vml, display, flt, classes, newClasses, head, fill, flex, foot;  
	var i, j, z, q, p, dist, stl, iter, rest, radi, higt, divs, opac, colr, bord, wide, half, ih, iw, ww, hh, fb, xb;  
	var itiltright, itiltnone, itiltleft, iheight, iopacity, idistance, iborder, icolor, iradius;
	var children = document.getElementsByTagName('img'); var tilt = 'r';
	for(i=0;i<theimages.length;i++) {	
		image = theimages[i]; object = image.parentNode; j = 0;
		itiltright = 0; itiltnone = 0; itiltleft = 0; 
		iheight = 33; iopacity = 33; idistance = 0;
		iborder = 0; icolor = '#000000'; iradius = 0; 
		if(image.width>=32 && image.height>=32) {
			classes = image.className.split(' ');
			iradius = getClassValue(classes,"iradius");
			iborder = getClassValue(classes,"iborder");
			iheight = getClassValue(classes,"iheight");
			iopacity = getClassValue(classes,"iopacity");
			idistance = getClassValue(classes,"idistance");
			icolor = getClassColor(classes,"icolor");
			itiltleft = getClassAttribute(classes,"itiltleft");
			itiltright = getClassAttribute(classes,"itiltright");
			itiltnone = getClassAttribute(classes,"itiltnone");
			if(itiltright==true) tilt = 'r';
			if(itiltnone==true) tilt = 'n';
			if(itiltleft==true) tilt = 'l';
			newClasses = getClasses(classes,"reflex");	
			ih = image.height; iw = image.width; dist = idistance; 
			radi = Math.min(iradius,Math.max(iw,ih)/10);
			colr = (icolor!=0?icolor:'#000000');
			opac = (iopacity>0?iopacity:33);
			divs = 100/(iheight>=10?iheight:33); 
			p = (iheight>=10?iheight:33)/100;
			higt = Math.floor(ih/divs); wide = 12;
			if(iborder==1) { bord = 0; }else {
				iborder = Math.floor(Math.round(Math.min(Math.min(iborder,higt/4),Math.max(iw,ih)/20))/2)*2;
				bord = (iborder>0?iborder/2:0); 
			}
			ww = parseInt(iw/20); q = 1;
			iter = Math.floor((iw-ww-ww)/wide); 
			rest = ((iw-ww-ww)%wide); half = (((iw-ww-ww)/wide)-1)/2;
			hh = iter+(rest>0?1:0); z = (ih-hh-hh)/ih;
			display = (image.currentStyle.display.toLowerCase()=='block')?'block':'inline-block';
			vml = document.createElement(['<var style="overflow:hidden;display:' + display + ';width:' + iw + 'px;height:' + (ih+higt+dist) + 'px;padding:0;">'].join(''));
			flt = image.currentStyle.styleFloat.toLowerCase();
			display = (flt=='left'||flt=='right')?'inline':display;
			head = '<v:group style="zoom:1; display:' + display + '; margin:-1px 0 0 -1px; padding:0; position:relative; width:' + iw + 'px;height:' + (ih+higt+dist) + 'px;" coordsize="' + iw + ',' + (ih+higt+dist) + '">';
			if(tilt=='n') {
				fill = '<v:rect strokeweight="0" filled="t" stroked="f" fillcolor="#ffffff" style="position:absolute; margin:-1px 0 0 -1px; padding:0; top:0px; left:0px; width:' + iw + 'px;height:' + ih + 'px;"><v:fill src="' + image.src + '" type="frame" /></v:rect>';
				fb = '<v:rect strokeweight="'+iborder+'" strokecolor="'+colr+'" filled="f" stroked="'+(bord>0||iborder>0?'t':'f')+'" fillcolor="#ffffff" style="position:absolute; margin:-1px 0 0 -1px; padding:0; top:'+bord+'px; left:'+bord+'px; width:'+(iw-bord-bord)+'px;height:'+(ih-bord-bord)+'px;"></v:rect>';
				xb = '<v:rect strokeweight="'+iborder+'" strokecolor="'+colr+'" filled="f" stroked="'+(bord>0||iborder>0?'t':'f')+'" fillcolor="#ffffff" style="position:absolute; margin:-1px 0 0 -1px; padding:0; top:'+(ih+dist+bord)+'px; left:'+bord+'px; width:'+(iw-bord-bord)+'px;height:'+(higt-bord-bord)+'px; filter: progid:DXImageTransform.Microsoft.Alpha(opacity='+opac+',style=1,finishOpacity=0,startx=0,starty=0,finishx=0,finishy='+parseInt(ih*0.66)+');"></v:rect>';
				flex = '<v:rect strokeweight="0" filled="t" stroked="f" fillcolor="#ffffff" style="position:absolute; margin:-1px 0 0 -1px; padding:0; top:'+(ih+dist)+'px; left:0px; width:' + iw + 'px;height:' + higt + 'px; filter:flipv progid:DXImageTransform.Microsoft.Alpha(opacity='+opac+',style=1,finishOpacity=0,startx=0,starty=0,finishx=0,finishy='+ih+');"><v:fill origin="0,0" position="0,-'+(divs/2-0.5)+'" size="1,'+(1*divs)+'" src="' + image.src + '" type="frame" /></v:rect>';
			}else if(tilt=='r') {
				fill = '<v:rect strokeweight="0" filled="t" stroked="f" fillcolor="#808080" style="position:absolute; margin:-1px 0 0 -1px;padding:0 ;width:' + iw + 'px;height:' + (ih+higt+dist) + 'px;"><v:fill color="#808080" opacity="0.0" /></v:rect><v:shape strokeweight="0" filled="t" stroked="f" fillcolor="#ffffff" coordorigin="0,0" coordsize="'+iw+','+ih+'" path="m '+ww+',0 l '+ww+','+ih+','+(iw-ww)+','+(ih-hh)+','+(iw-ww)+','+hh+' x e" style="position:absolute; margin:-1px 0 0 -1px; padding:0; top:0px; left:0px; width:' + iw + 'px;height:' + ih + 'px;"><v:fill src="' + image.src + '" type="frame" /></v:shape>';
				for(j=0;j<iter;j++) {
					if(j==(iter-1)) q = (rest>0?1:0);
					fill += '<v:shape strokeweight="0" filled="t" stroked="f" fillcolor="#808080" coordorigin="0,0" coordsize="'+iw+','+ih+'" path="m '+(ww+(j*wide))+','+j+' l '+(q+ww+((j+1)*wide))+','+(j+1)+','+(q+ww+((j+1)*wide))+','+(ih-1-j)+','+(ww+(j*wide))+','+(ih-j)+' x e" style="position:absolute; margin: -1px 0 0 -1px; padding:0px; top:0px; left:0px; width:' + iw + 'px; height:' + ih + 'px;"><v:fill origin="0,0" position="'+(half-j)+',0" size="'+((iw-ww-ww)/wide)+',1" type="frame" src="' + image.src + '" /></v:shape>';
				}
				if(rest>0) {
					fill += '<v:shape strokeweight="0" filled="t" stroked="f" fillcolor="#808080" coordorigin="0,0" coordsize="'+iw+','+ih+'" path="m '+(ww+(j*wide))+','+j+' l '+(ww+((j+1)*wide))+','+(j+1)+','+(ww+((j+1)*wide))+','+(ih-1-j)+','+(ww+(j*wide))+','+(ih-j)+' x e" style="position:absolute; margin: -1px 0 0 -1px; padding:0px; top:0px; left:0px; width:' + iw + 'px; height:' + ih + 'px;"><v:fill origin="0,0" position="'+(half-j)+',0" size="'+((iw-ww-ww)/wide)+',1" type="frame" src="' + image.src + '" /></v:shape>';
				}
				q = ((iter*z)/(ih/100))/2; 
				if(bord>0||iborder>0) {
					fb = '<v:shape strokeweight="'+iborder+'" strokecolor="'+colr+'" filled="f" stroked="'+(bord>0||iborder>0?'t':'f')+'" coordorigin="0,0" coordsize="'+iw+','+ih+'" path="m '+(ww+bord)+','+bord+' l '+(ww+bord)+','+(ih-bord)+','+(iw-ww-bord)+','+(ih-hh-bord)+','+(iw-ww-bord)+','+(hh+bord)+' x e" style="position:absolute; margin:-1px 0 0 -1px; padding:0; top:0px; left:0px; width:' + iw + 'px;height:' + ih + 'px;"></v:shape>';
					xb = '<v:shape strokeweight="'+iborder+'" strokecolor="'+colr+'" stroked="'+(bord>0||iborder>0?'t':'f')+'" filled="f" coordorigin="0,0" coordsize="'+iw+','+(hh+higt+dist)+'" path="m '+(ww+bord)+','+(hh+dist+bord)+' l '+(ww+bord)+','+(higt+hh+dist-bord)+','+(iw-ww-bord)+','+(parseInt((higt+dist)*z)-bord)+','+(iw-ww-bord)+','+(parseInt(dist*z)+bord)+' x e" style="position:absolute; margin:-1px 0 0 -1px; padding:0; top:'+(ih-hh+dist)+'px; left:0px; width:' + iw + 'px;height:' + (hh+higt+dist) + 'px; flip: y; filter:flipv progid:DXImageTransform.Microsoft.Alpha(opacity='+opac+',style=1,finishOpacity=0,startx=0,starty=0,finishx='+q+',finishy=80);"></v:shape>';
				}else {fb = ''; xb = ''; }	
				flex = '<v:shape strokeweight="0" stroked="f" filled="t" fillcolor="#808080" coordorigin="0,0" coordsize="'+iw+','+(hh+higt+dist)+'" path="m '+ww+','+(hh+dist)+' l '+ww+','+(higt+hh+dist)+','+(iw-ww)+','+parseInt((higt+dist)*z)+','+(iw-ww)+','+parseInt(dist*z)+' x e" style="position:absolute; margin:-1px 0 0 -1px; padding:0; top:'+(ih-hh+dist)+'px; left:0px; width:' + iw + 'px;height:' + (hh+higt+dist) + 'px; flip: y; filter:flipv progid:DXImageTransform.Microsoft.Alpha(opacity='+opac+',style=1,finishOpacity=0,startx=0,starty=0,finishx='+q+',finishy=90);"><v:fill origin="0,0" position="0,-'+((divs/2)-0.5)+'" size="1,'+(divs)+'" src="' + image.src + '" type="frame" /></v:shape>';
			}else if(tilt=='l') {
				fill = '<v:rect strokeweight="0" filled="t" stroked="f" fillcolor="#808080" style="position:absolute; margin:-1px 0 0 -1px;padding:0 ;width:' + iw + 'px;height:' + (ih+higt+dist) + 'px;"><v:fill color="#808080" opacity="0.0" /></v:rect><v:shape strokeweight="0" filled="t" stroked="f" fillcolor="#ffffff" coordorigin="0,0" coordsize="'+iw+','+ih+'" path="m '+ww+','+hh+' l '+ww+','+(ih-hh)+','+(iw-ww)+','+ih+','+(iw-ww)+',0 x e" style="position:absolute; margin:-1px 0 0 -1px; padding:0; top:0px; left:0px; width:' + iw + 'px;height:' + ih + 'px;"><v:fill src="' + image.src + '" type="frame" /></v:shape>';
				for(j=0;j<iter;j++) {
					if(j==(iter-1)) q = (rest>0?1:0);
					fill += '<v:shape strokeweight="0" filled="t" stroked="f" fillcolor="#808080" coordorigin="0,0" coordsize="'+iw+','+ih+'" path="m '+(ww+(j*wide))+','+(iter-j)+' l '+(q+ww+((j+1)*wide))+','+(iter-1-j)+','+(q+ww+((j+1)*wide))+','+(ih-1-iter+j)+','+(ww+(j*wide))+','+(ih-iter+j)+' x e" style="position:absolute; margin: -1px 0 0 -1px; padding:0px; top:0px; left:0px; width:' + iw + 'px; height:' + ih + 'px;"><v:fill origin="0,0" position="'+(half-j)+',0" size="'+((iw-ww-ww)/wide)+',1" type="frame" src="' + image.src + '" /></v:shape>';
				}
				if(rest>0) {
					fill += '<v:shape strokeweight="0" filled="t" stroked="f" fillcolor="#808080" coordorigin="0,0" coordsize="'+iw+','+ih+'" path="m '+(ww+(j*wide))+','+(iter-j)+' l '+(ww+((j+1)*wide))+','+(iter-1-j)+','+(ww+((j+1)*wide))+','+(ih-1-iter+j)+','+(ww+(j*wide))+','+(ih-iter+j)+' x e" style="position:absolute; margin: -1px 0 0 -1px; padding:0px; top:0px; left:0px; width:' + iw + 'px; height:' + ih + 'px;"><v:fill origin="0,0" position="'+(half-j)+',0" size="'+((iw-ww-ww)/wide)+',1" type="frame" src="' + image.src + '" /></v:shape>';
				}
				q = 100-(((iter*z)/(ih/100))/2); 
				if(bord>0||iborder>0) {
					fb = '<v:shape strokeweight="'+iborder+'" strokecolor="'+colr+'" filled="f" stroked="'+(bord>0||iborder>0?'t':'f')+'" coordorigin="0,0" coordsize="'+iw+','+ih+'" path="m '+(ww+bord)+','+(hh+bord)+' l '+(ww+bord)+','+(ih-hh-bord)+','+(iw-ww-bord)+','+(ih-bord)+','+(iw-ww-bord)+','+bord+' x e" style="position:absolute; margin:-1px 0 0 -1px; padding:0; top:0px; left:0px; width:' + iw + 'px;height:' + ih + 'px;"></v:shape>';
					xb = '<v:shape strokeweight="'+iborder+'" strokecolor="'+colr+'" stroked="'+(bord>0||iborder>0?'t':'f')+'" filled="f" coordorigin="0,0" coordsize="'+iw+','+(hh+higt+dist)+'" path="m '+(ww+bord)+','+(parseInt(dist*z)+bord)+' l '+(ww+bord)+','+(parseInt((higt+dist)*z)-bord)+','+(iw-ww-bord)+','+(higt+hh+dist-bord)+','+(iw-ww-bord)+','+(hh+dist+bord)+' x e" style="position:absolute; margin:-1px 0 0 -1px; padding:0; top:'+(ih-hh+dist)+'px; left:0px; width:' + iw + 'px;height:' + (hh+higt+dist) + 'px; flip: y; filter:flipv progid:DXImageTransform.Microsoft.Alpha(opacity='+opac+',style=1,finishOpacity=0,startx=100,starty=0,finishx='+q+',finishy=80);"></v:shape>';
				}else {fb = ''; xb = ''; }
				flex = '<v:shape strokeweight="0" filled="t" stroked="f" fillcolor="#808080" coordorigin="0,0" coordsize="'+iw+','+(hh+higt+dist)+'" path="m '+ww+','+parseInt(dist*z)+' l '+ww+','+parseInt((higt+dist)*z)+','+(iw-ww)+','+(higt+hh+dist)+','+(iw-ww)+','+(hh+dist)+' x e" style="position:absolute; margin:-1px 0 0 -1px; padding:0; top:'+(ih-hh+dist)+'px; left:0px; width:' + iw + 'px;height:' + (hh+higt+dist) + 'px; flip: y; filter:flipv progid:DXImageTransform.Microsoft.Alpha(opacity='+opac+',style=1,finishOpacity=0,startx=100,starty=0,finishx='+q+',finishy=90);"><v:fill origin="0,0" position="0,-'+((divs/2)-0.5)+'" size="1,'+(divs)+'" src="' + image.src + '" type="frame" /></v:shape>';
			}
			foot = '</v:group>';
			vml.innerHTML = head+flex+xb+fill+fb+foot;
			vml.className = newClasses;
			vml.style.cssText = image.style.cssText;
			vml.style.height = ih+higt+dist+'px'; vml.width = iw;
			vml.height = ih+higt+dist; vml.style.width = iw+'px';
			vml.src = image.src; vml.alt = image.alt;
			if(image.id!='') vml.id = image.id; 
			if(image.title!='') vml.title = image.title;
			if(image.getAttribute('onclick')!='') vml.setAttribute('onclick',image.getAttribute('onclick'));
			object.replaceChild(vml,image);
			if(tilt=='r') {tilt='n';}else if(tilt=='n') {tilt='l';}else if(tilt=='l') {tilt='r';}
			vml.style.visibility = 'visible';
		}
	}
}

function addReflex() {
	var theimages = getImages('reflex');
	var image, object, canvas, context, classes, newClasses, resource, tmp;  
	var i, j, dist, stl, iter, rest, radi, higt, divs, opac, colr, bord, wide, ih, iw;  
	var itiltright, itiltnone, itiltleft, iheight, iopacity, idistance, iborder, icolor, iradius;
	var children = document.getElementsByTagName('img'); var tilt = 'r';
	var isWK = navigator.appVersion.indexOf('WebKit')!=-1?1:0; var isOP = window.opera?1:0;
	var isW5 = document.defaultCharset&&!window.execScript?1:0;
	for(i=0;i<theimages.length;i++) {	
		image = theimages[i]; object = image.parentNode; tmp = 0;
		itiltright = 0; itiltnone = 0; itiltleft = 0; 
		iheight = 33; iopacity = 33; idistance = 0;
		iborder = 0; icolor = '#000000'; iradius = 0; 
		canvas = document.createElement('canvas');
		if(canvas.getContext && image.width>=32 && image.height>=32) {
			classes = image.className.split(' ');
			iradius = getClassValue(classes,"iradius");
			iborder = getClassValue(classes,"iborder");
			iheight = getClassValue(classes,"iheight");
			iopacity = getClassValue(classes,"iopacity");
			idistance = getClassValue(classes,"idistance");
			icolor = getClassColor(classes,"icolor");
			itiltleft = getClassAttribute(classes,"itiltleft");
			itiltright = getClassAttribute(classes,"itiltright");
			itiltnone = getClassAttribute(classes,"itiltnone");
			if(itiltright==true) tilt = 'r';
			if(itiltnone==true) tilt = 'n';
			if(itiltleft==true) tilt = 'l';
			newClasses = getClasses(classes,"reflex");	
			ih = image.height; iw = image.width; dist = idistance; 
			radi = Math.min(iradius,Math.max(iw,ih)/10);
			colr = (icolor!=0?icolor:'#000000');
			opac = (100-(iopacity>0?iopacity:33))/100;
			divs = 100/(iheight>=10?iheight:33);
			higt = Math.floor(image.height/divs);
			iborder = Math.round(Math.min(Math.min(iborder,higt/4),Math.max(iw,ih)/20));
			wide = 12; bord = (iborder>0?iborder/2:0);
			canvas.className = newClasses;
			canvas.style.cssText = image.style.cssText;
			canvas.style.height = ih+higt+dist+'px'; canvas.width = iw;
			canvas.style.width = iw+'px'; canvas.height = ih+higt+dist;
			canvas.src = image.src; canvas.alt = image.alt;
			if(image.id!='') canvas.id = image.id;
			if(image.title!='') canvas.title = image.title;
			if(image.getAttribute('onclick')!='') canvas.setAttribute('onclick',image.getAttribute('onclick'));
			iter = Math.floor(canvas.width/wide); rest = (canvas.width%wide);
			if(tilt=='l'||tilt=='r') {
				resource = document.createElement('canvas');
				if(resource.getContext) {
					resource.style.position = 'fixed';
					resource.style.left = -9999+'px';
					resource.style.top = 0+'px';
					resource.height = canvas.height;
					resource.width = canvas.width;
					resource.style.height = canvas.height+'px';
					resource.style.width = canvas.width+'px';
					if(isWK&&!isW5) {object.appendChild(resource);}
				}
			}
			context = canvas.getContext("2d");
			object.replaceChild(canvas,image);
			context.clearRect(0,0,canvas.width,canvas.height);
			context.globalCompositeOperation = "source-over";
			context.fillStyle = 'rgba(0,0,0,0)';
			context.fillRect(0,0,canvas.width,canvas.height);
			context.save();
			context.translate(0,canvas.height);
			context.scale(1,-1);
			context.drawImage(image,0,-(canvas.height-higt-higt-dist),canvas.width,canvas.height-higt-dist);
			context.restore();
			if(iborder>0) {
				context.strokeStyle = colr;
				context.lineWidth = iborder;
				context.beginPath(); 
				context.rect(bord,canvas.height-higt+bord,canvas.width-iborder,higt);
				context.closePath();
				context.stroke();
			}
			if(!isWK||tilt=='n') {
				context.globalCompositeOperation = "destination-out";
				stl = context.createLinearGradient(0,canvas.height-higt,0,canvas.height);
				stl.addColorStop(1,"rgba(0,0,0,1.0)");
				stl.addColorStop(0,"rgba(0,0,0,"+opac+")");
				context.fillStyle = stl;
			}
			if(isWK) {
				context.beginPath(); 
				context.rect(0,canvas.height-higt,canvas.width,higt);
				context.closePath();
				context.fill();
			}else {
				context.fillRect(0,canvas.height-higt,canvas.width,higt);
			}
			context.globalCompositeOperation = "source-over";
			context.drawImage(image,0,0,iw,ih);
			context.save();
			if(isWK&&dist>0&&tilt!='n') {
				context.fillStyle = '#808080';
				context.fillRect(0,canvas.height-higt-dist,canvas.width,dist);
			}
			if(iborder>0) {
				if(tilt=='n') {
					context.beginPath(); 
					context.rect(bord,bord,canvas.width-iborder,canvas.height-higt-dist-iborder);
					context.closePath();
					context.stroke();
				}
			}
			if(tilt=='l'||tilt=='r') {
				if(resource.getContext) {
					context = resource.getContext("2d");
					context.globalCompositeOperation = "source-over";
					context.clearRect(0,0,resource.width,resource.height);					
					if(tilt=='r') {
						for(j=0;j<iter;j++) {
							context.drawImage(canvas,j*wide,0,wide,resource.height,j*wide,j*1,wide,resource.height-(j*2));
						}
						if(rest>0) {
							rest = canvas.width-(iter*wide);
							context.drawImage(canvas,j*wide,0,rest,resource.height,j*wide,j*1,rest,resource.height-(j*2));
						}
					}else {
						for(j=0;j<iter;j++) {
							context.drawImage(canvas,j*wide,0,wide,resource.height,j*wide,(iter-j)*1,wide,resource.height-((iter-j)*2));
						}
						if(rest>0) {
							rest = canvas.width-(iter*wide);
							context.drawImage(canvas,j*wide,0,rest,resource.height,j*wide,0,rest,resource.height);
						}
					}
					context.save();
					if(canvas.getContext) {
						context = canvas.getContext("2d");
						context.clearRect(0,0,canvas.width,canvas.height);						
						if(tilt=='r') {
							clipPolyRight(context,canvas.width/20,0,canvas.width*0.95,canvas.height,iter+(rest>0?1:0),dist,higt);
						}else {
							clipPolyLeft(context,canvas.width/20,0,canvas.width*0.95,canvas.height,iter+(rest>0?1:1),dist,higt);
						}
						context.clip();
						context.drawImage(resource,parseInt(canvas.width/20),0,parseInt(canvas.width*0.9),canvas.height);
						context.save();
						if(iborder>0) {
							context.lineWidth = iborder;
							if(tilt=='r') {
								strokePolyRight(context,canvas.width/20,0,canvas.width*0.95,canvas.height,iter+(rest>0?1:0),dist,higt,bord);
								context.stroke();
							}else {
								strokePolyLeft(context,canvas.width/20,0,canvas.width*0.95,canvas.height,iter+(rest>0?1:0),dist,higt,bord);
								context.stroke();
							}
						}
						if(isWK) {
							context.globalCompositeOperation = "destination-out";
							stl = context.createLinearGradient((tilt=='l'?canvas.width:0),canvas.height-higt,(tilt=='l'?canvas.width-parseInt(wide/divs):parseInt(wide/divs)),canvas.height);
							stl.addColorStop(1,"rgba(255,0,0,1.0)");
							stl.addColorStop(0,"rgba(255,0,0,"+opac+")");
							context.fillStyle = stl;
							clipReflex(context,canvas.width/20,0,canvas.width*0.95,canvas.height,iter+(rest>0?1:0),dist,higt,tilt);
							context.fill();
							globalCompositeOperation = "source-in";
							clearReflex(context,canvas.width/20,0,canvas.width*0.95,canvas.height,iter+(rest>0?1:0),dist,higt,tilt);
							context.clip();
							context.clearRect(0,0,canvas.width,canvas.height);
							context.clearRect(0,0,canvas.width,canvas.height);
							context.clearRect(0,0,canvas.width,canvas.height);
							context.clearRect(0,0,canvas.width,canvas.height);
							if(isWK&&!isW5) {object.removeChild(resource);}
						}
					}
				}
			}
			if(tilt=='r') {tilt='n';}else if(tilt=='n') {tilt='l';}else if(tilt=='l') {tilt='r';}
			context.save();
			canvas.style.visibility = 'visible';
		}
	}
}

var reflexOnload = window.onload;
window.onload = function () { if(reflexOnload) reflexOnload(); if(isIE){addIEReflex(); }else {addReflex(); }}




/*
  SortTable
  version 2
  7th April 2007
  Stuart Langridge, http://www.kryogenix.org/code/browser/sorttable/
  
  Instructions:
  Download this file
  Add <script src="sorttable.js"></script> to your HTML
  Add class="sortable" to any table you'd like to make sortable
  Click on the headers to sort
  
  Thanks to many, many people for contributions and suggestions.
  Licenced as X11: http://www.kryogenix.org/code/browser/licence.html
  This basically means: do what you want with it.
*/

 
var stIsIE = /*@cc_on!@*/false;

sorttable = {
  init: function() {
    // quit if this function has already been called
    if (arguments.callee.done) return;
    // flag this function so we don't do the same thing twice
    arguments.callee.done = true;
    // kill the timer
    if (_timer) clearInterval(_timer);
    
    if (!document.createElement || !document.getElementsByTagName) return;
    
    sorttable.DATE_RE = /^(\d\d?)[\/\.-](\d\d?)[\/\.-]((\d\d)?\d\d)$/;
    
    forEach(document.getElementsByTagName('table'), function(table) {
      if (table.className.search(/\bsortable\b/) != -1) {
        sorttable.makeSortable(table);
      }
    });
    
  },
  
  makeSortable: function(table) {
    if (table.getElementsByTagName('thead').length == 0) {
      // table doesn't have a tHead. Since it should have, create one and
      // put the first table row in it.
      the = document.createElement('thead');
      the.appendChild(table.rows[0]);
      table.insertBefore(the,table.firstChild);
    }
    // Safari doesn't support table.tHead, sigh
    if (table.tHead == null) table.tHead = table.getElementsByTagName('thead')[0];
    
    if (table.tHead.rows.length != 1) return; // can't cope with two header rows
    
    // Sorttable v1 put rows with a class of "sortbottom" at the bottom (as
    // "total" rows, for example). This is B&R, since what you're supposed
    // to do is put them in a tfoot. So, if there are sortbottom rows,
    // for backwards compatibility, move them to tfoot (creating it if needed).
    sortbottomrows = [];
    for (var i=0; i<table.rows.length; i++) {
      if (table.rows[i].className.search(/\bsortbottom\b/) != -1) {
        sortbottomrows[sortbottomrows.length] = table.rows[i];
      }
    }
    if (sortbottomrows) {
      if (table.tFoot == null) {
        // table doesn't have a tfoot. Create one.
        tfo = document.createElement('tfoot');
        table.appendChild(tfo);
      }
      for (var i=0; i<sortbottomrows.length; i++) {
        tfo.appendChild(sortbottomrows[i]);
      }
      delete sortbottomrows;
    }
    
    // work through each column and calculate its type
    headrow = table.tHead.rows[0].cells;
    for (var i=0; i<headrow.length; i++) {
      // manually override the type with a sorttable_type attribute
      if (!headrow[i].className.match(/\bsorttable_nosort\b/)) { // skip this col
        mtch = headrow[i].className.match(/\bsorttable_([a-z0-9]+)\b/);
        if (mtch) { override = mtch[1]; }
	      if (mtch && typeof sorttable["sort_"+override] == 'function') {
	        headrow[i].sorttable_sortfunction = sorttable["sort_"+override];
	      } else {
	        headrow[i].sorttable_sortfunction = sorttable.guessType(table,i);
	      }
	      // make it clickable to sort
	      headrow[i].sorttable_columnindex = i;
	      headrow[i].sorttable_tbody = table.tBodies[0];
	      dean_addEvent(headrow[i],"click", function(e) {

          if (this.className.search(/\bsorttable_sorted\b/) != -1) {
            // if we're already sorted by this column, just 
            // reverse the table, which is quicker
            sorttable.reverse(this.sorttable_tbody);
            this.className = this.className.replace('sorttable_sorted',
                                                    'sorttable_sorted_reverse');
            this.removeChild(document.getElementById('sorttable_sortfwdind'));
            sortrevind = document.createElement('span');
            sortrevind.id = "sorttable_sortrevind";
            sortrevind.innerHTML = stIsIE ? '&nbsp<font face="webdings">5</font>' : '&nbsp;&#x25B4;';
            this.appendChild(sortrevind);
            return;
          }
          if (this.className.search(/\bsorttable_sorted_reverse\b/) != -1) {
            // if we're already sorted by this column in reverse, just 
            // re-reverse the table, which is quicker
            sorttable.reverse(this.sorttable_tbody);
            this.className = this.className.replace('sorttable_sorted_reverse',
                                                    'sorttable_sorted');
            this.removeChild(document.getElementById('sorttable_sortrevind'));
            sortfwdind = document.createElement('span');
            sortfwdind.id = "sorttable_sortfwdind";
            sortfwdind.innerHTML = stIsIE ? '&nbsp<font face="webdings">6</font>' : '&nbsp;&#x25BE;';
            this.appendChild(sortfwdind);
            return;
          }
          
          // remove sorttable_sorted classes
          theadrow = this.parentNode;
          forEach(theadrow.childNodes, function(cell) {
            if (cell.nodeType == 1) { // an element
              cell.className = cell.className.replace('sorttable_sorted_reverse','');
              cell.className = cell.className.replace('sorttable_sorted','');
            }
          });
          sortfwdind = document.getElementById('sorttable_sortfwdind');
          if (sortfwdind) { sortfwdind.parentNode.removeChild(sortfwdind); }
          sortrevind = document.getElementById('sorttable_sortrevind');
          if (sortrevind) { sortrevind.parentNode.removeChild(sortrevind); }
          
          this.className += ' sorttable_sorted';
          sortfwdind = document.createElement('span');
          sortfwdind.id = "sorttable_sortfwdind";
          sortfwdind.innerHTML = stIsIE ? '&nbsp<font face="webdings">6</font>' : '&nbsp;&#x25BE;';
          this.appendChild(sortfwdind);

	        // build an array to sort. This is a Schwartzian transform thing,
	        // i.e., we "decorate" each row with the actual sort key,
	        // sort based on the sort keys, and then put the rows back in order
	        // which is a lot faster because you only do getInnerText once per row
	        row_array = [];
	        col = this.sorttable_columnindex;
	        rows = this.sorttable_tbody.rows;
	        for (var j=0; j<rows.length; j++) {
	          row_array[row_array.length] = [sorttable.getInnerText(rows[j].cells[col]), rows[j]];
	        }
	        /* If you want a stable sort, uncomment the following line */
	        //sorttable.shaker_sort(row_array, this.sorttable_sortfunction);
	        /* and comment out this one */
	        row_array.sort(this.sorttable_sortfunction);
	        
	        tb = this.sorttable_tbody;
	        for (var j=0; j<row_array.length; j++) {
	          tb.appendChild(row_array[j][1]);
	        }
	        
	        delete row_array;
	      });
	    }
    }
  },
  
  guessType: function(table, column) {
    // guess the type of a column based on its first non-blank row
    sortfn = sorttable.sort_alpha;
    for (var i=0; i<table.tBodies[0].rows.length; i++) {
      text = sorttable.getInnerText(table.tBodies[0].rows[i].cells[column]);
      if (text != '') {
        if (text.match(/^-?[£$¤]?[\d,.]+%?$/)) {
          return sorttable.sort_numeric;
        }
        // check for a date: dd/mm/yyyy or dd/mm/yy 
        // can have / or . or - as separator
        // can be mm/dd as well
        possdate = text.match(sorttable.DATE_RE)
        if (possdate) {
          // looks like a date
          first = parseInt(possdate[1]);
          second = parseInt(possdate[2]);
          if (first > 12) {
            // definitely dd/mm
            return sorttable.sort_ddmm;
          } else if (second > 12) {
            return sorttable.sort_mmdd;
          } else {
            // looks like a date, but we can't tell which, so assume
            // that it's dd/mm (English imperialism!) and keep looking
            sortfn = sorttable.sort_ddmm;
          }
        }
      }
    }
    return sortfn;
  },
  
  getInnerText: function(node) {
    // gets the text we want to use for sorting for a cell.
    // strips leading and trailing whitespace.
    // this is *not* a generic getInnerText function; it's special to sorttable.
    // for example, you can override the cell text with a customkey attribute.
    // it also gets .value for <input> fields.
    
    hasInputs = (typeof node.getElementsByTagName == 'function') &&
                 node.getElementsByTagName('input').length;
    
    if (node.getAttribute("sorttable_customkey") != null) {
      return node.getAttribute("sorttable_customkey");
    }
    else if (typeof node.textContent != 'undefined' && !hasInputs) {
      return node.textContent.replace(/^\s+|\s+$/g, '');
    }
    else if (typeof node.innerText != 'undefined' && !hasInputs) {
      return node.innerText.replace(/^\s+|\s+$/g, '');
    }
    else if (typeof node.text != 'undefined' && !hasInputs) {
      return node.text.replace(/^\s+|\s+$/g, '');
    }
    else {
      switch (node.nodeType) {
        case 3:
          if (node.nodeName.toLowerCase() == 'input') {
            return node.value.replace(/^\s+|\s+$/g, '');
          }
        case 4:
          return node.nodeValue.replace(/^\s+|\s+$/g, '');
          break;
        case 1:
        case 11:
          var innerText = '';
          for (var i = 0; i < node.childNodes.length; i++) {
            innerText += sorttable.getInnerText(node.childNodes[i]);
          }
          return innerText.replace(/^\s+|\s+$/g, '');
          break;
        default:
          return '';
      }
    }
  },
  
  reverse: function(tbody) {
    // reverse the rows in a tbody
    newrows = [];
    for (var i=0; i<tbody.rows.length; i++) {
      newrows[newrows.length] = tbody.rows[i];
    }
    for (var i=newrows.length-1; i>=0; i--) {
       tbody.appendChild(newrows[i]);
    }
    delete newrows;
  },
  
  /* sort functions
     each sort function takes two parameters, a and b
     you are comparing a[0] and b[0] */
  sort_numeric: function(a,b) {
    aa = parseFloat(a[0].replace(/[^0-9.-]/g,''));
    if (isNaN(aa)) aa = 0;
    bb = parseFloat(b[0].replace(/[^0-9.-]/g,'')); 
    if (isNaN(bb)) bb = 0;
    return aa-bb;
  },
  sort_alpha: function(a,b) {
    if (a[0]==b[0]) return 0;
    if (a[0]<b[0]) return -1;
    return 1;
  },
  sort_ddmm: function(a,b) {
    mtch = a[0].match(sorttable.DATE_RE);
    y = mtch[3]; m = mtch[2]; d = mtch[1];
    if (m.length == 1) m = '0'+m;
    if (d.length == 1) d = '0'+d;
    dt1 = y+m+d;
    mtch = b[0].match(sorttable.DATE_RE);
    y = mtch[3]; m = mtch[2]; d = mtch[1];
    if (m.length == 1) m = '0'+m;
    if (d.length == 1) d = '0'+d;
    dt2 = y+m+d;
    if (dt1==dt2) return 0;
    if (dt1<dt2) return -1;
    return 1;
  },
  sort_mmdd: function(a,b) {
    mtch = a[0].match(sorttable.DATE_RE);
    y = mtch[3]; d = mtch[2]; m = mtch[1];
    if (m.length == 1) m = '0'+m;
    if (d.length == 1) d = '0'+d;
    dt1 = y+m+d;
    mtch = b[0].match(sorttable.DATE_RE);
    y = mtch[3]; d = mtch[2]; m = mtch[1];
    if (m.length == 1) m = '0'+m;
    if (d.length == 1) d = '0'+d;
    dt2 = y+m+d;
    if (dt1==dt2) return 0;
    if (dt1<dt2) return -1;
    return 1;
  },
  
  shaker_sort: function(list, comp_func) {
    // A stable sort function to allow multi-level sorting of data
    // see: http://en.wikipedia.org/wiki/Cocktail_sort
    // thanks to Joseph Nahmias
    var b = 0;
    var t = list.length - 1;
    var swap = true;

    while(swap) {
        swap = false;
        for(var i = b; i < t; ++i) {
            if ( comp_func(list[i], list[i+1]) > 0 ) {
                var q = list[i]; list[i] = list[i+1]; list[i+1] = q;
                swap = true;
            }
        } // for
        t--;

        if (!swap) break;

        for(var i = t; i > b; --i) {
            if ( comp_func(list[i], list[i-1]) < 0 ) {
                var q = list[i]; list[i] = list[i-1]; list[i-1] = q;
                swap = true;
            }
        } // for
        b++;

    } // while(swap)
  }  
}

/* ******************************************************************
   Supporting functions: bundled here to avoid depending on a library
   ****************************************************************** */

// Dean Edwards/Matthias Miller/John Resig

/* for Mozilla/Opera9 */
if (document.addEventListener) {
    document.addEventListener("DOMContentLoaded", sorttable.init, false);
}

/* for Internet Explorer */
/*@cc_on @*/
/*@if (@_win32)
    document.write("<script id=__ie_onload defer src=javascript:void(0)><\/script>");
    var script = document.getElementById("__ie_onload");
    script.onreadystatechange = function() {
        if (this.readyState == "complete") {
            sorttable.init(); // call the onload handler
        }
    };
/*@end @*/

/* for Safari */
if (/WebKit/i.test(navigator.userAgent)) { // sniff
    var _timer = setInterval(function() {
        if (/loaded|complete/.test(document.readyState)) {
            sorttable.init(); // call the onload handler
        }
    }, 10);
}

/* for other browsers */
window.onload = sorttable.init;

// written by Dean Edwards, 2005
// with input from Tino Zijdel, Matthias Miller, Diego Perini

// http://dean.edwards.name/weblog/2005/10/add-event/

function dean_addEvent(element, type, handler) {
	if (element.addEventListener) {
		element.addEventListener(type, handler, false);
	} else {
		// assign each event handler a unique ID
		if (!handler.$$guid) handler.$$guid = dean_addEvent.guid++;
		// create a hash table of event types for the element
		if (!element.events) element.events = {};
		// create a hash table of event handlers for each element/event pair
		var handlers = element.events[type];
		if (!handlers) {
			handlers = element.events[type] = {};
			// store the existing event handler (if there is one)
			if (element["on" + type]) {
				handlers[0] = element["on" + type];
			}
		}
		// store the event handler in the hash table
		handlers[handler.$$guid] = handler;
		// assign a global event handler to do all the work
		element["on" + type] = handleEvent;
	}
};
// a counter used to create unique IDs
dean_addEvent.guid = 1;

function removeEvent(element, type, handler) {
	if (element.removeEventListener) {
		element.removeEventListener(type, handler, false);
	} else {
		// delete the event handler from the hash table
		if (element.events && element.events[type]) {
			delete element.events[type][handler.$$guid];
		}
	}
};

function handleEvent(event) {
	var returnValue = true;
	// grab the event object (IE uses a global event object)
	event = event || fixEvent(((this.ownerDocument || this.document || this).parentWindow || window).event);
	// get a reference to the hash table of event handlers
	var handlers = this.events[event.type];
	// execute each event handler
	for (var i in handlers) {
		this.$$handleEvent = handlers[i];
		if (this.$$handleEvent(event) === false) {
			returnValue = false;
		}
	}
	return returnValue;
};

function fixEvent(event) {
	// add W3C standard event methods
	event.preventDefault = fixEvent.preventDefault;
	event.stopPropagation = fixEvent.stopPropagation;
	return event;
};
fixEvent.preventDefault = function() {
	this.returnValue = false;
};
fixEvent.stopPropagation = function() {
  this.cancelBubble = true;
}

// Dean's forEach: http://dean.edwards.name/base/forEach.js
/*
	forEach, version 1.0
	Copyright 2006, Dean Edwards
	License: http://www.opensource.org/licenses/mit-license.php
*/

// array-like enumeration
if (!Array.forEach) { // mozilla already supports this
	Array.forEach = function(array, block, context) {
		for (var i = 0; i < array.length; i++) {
			block.call(context, array[i], i, array);
		}
	};
}

// generic enumeration
Function.prototype.forEach = function(object, block, context) {
	for (var key in object) {
		if (typeof this.prototype[key] == "undefined") {
			block.call(context, object[key], key, object);
		}
	}
};

// character enumeration
String.forEach = function(string, block, context) {
	Array.forEach(string.split(""), function(chr, index) {
		block.call(context, chr, index, string);
	});
};

// globally resolve forEach enumeration
var forEach = function(object, block, context) {
	if (object) {
		var resolve = Object; // default
		if (object instanceof Function) {
			// functions have a "length" property
			resolve = Function;
		} else if (object.forEach instanceof Function) {
			// the object implements a custom forEach method so use that
			object.forEach(block, context);
			return;
		} else if (typeof object == "string") {
			// the object is a string
			resolve = String;
		} else if (typeof object.length == "number") {
			// the object is array-like
			resolve = Array;
		}
		resolve.forEach(object, block, context);
	}
};



