String.prototype.trim = function() {
	a = this.replace(/^\s+/, '');
	return a.replace(/\s+$/, '');
};

Ptg = {};

Ptg.$ = jQuery.noConflict();

Ptg.overlay = undefined;
Ptg.window = undefined;

/**
* Returns the value of the selected radio button in the radio group, null if
* none are selected, and false if the button group doesn't exist
*
* @param {radio Object} or {radio id} el
* OR
* @param {form Object} or {form id} el
* @param {radio group name} radioGroup
*/
function $RF(el, radioGroup) {
    if($(el).type && $(el).type.toLowerCase() == 'radio') {
        var radioGroup = $(el).name;
        var el = $(el).form;
    } else if ($(el).tagName.toLowerCase() != 'form') {
        return false;
    }

    var radios = $(el).getInputs('radio', radioGroup);
    if (radios.length == 0) {
    	return false;
    }

    var checked = radios.find(
        function(re) {
        	return re.checked;
        }
    );
    return (checked) ? $F(checked) : null;
}

Ptg.addTrailingSlash = function (str) {
    if ( str.charAt(str.length - 1) != '/' ) {
        return str + '/';
    } else {
        return str;
    }
};

Ptg.CheckEmail = function (email) {
	return email.match(/^[a-z0-9!#$%&\'*+\/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&\'*+\/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+(?:[A-Z]{2}|com|org|net|gov|mil|biz|info|name|aero|biz|info|mobi|jobs|museum)\b$/im);
};

Ptg.forceNumericInput = function (ieChar, mozChar) {
    // this function wont prevent pasting non numeric values in the field!
    var retVal;

    if( mozChar != null ) { // Mozilla-compatible browser
        retVal = ((mozChar >= 48 && mozChar <= 57) || mozChar == 0 || ieChar == 8 || ieChar == 13);
    } else { // Must be an IE-compatible Browser
        retVal = ((ieChar >= 48 && ieChar <= 57) || ieChar == 13);
    }

    return retVal;
};

Ptg.trim = function (str) {
    return str.replace(/^\s+/, "").replace(/\s+$/, "");
};

Ptg.isNumeric = function (str) {
    return !/\D/.test(str);
};

Ptg.slideDownOnce = function (element) {
    if (!$(element).visible()) {
    	Effect.SlideDown(element);
    }
};

Ptg.checkMiniQuizAnswersValidity = function () {
    var isValid;

    if ( !(document.form1.answer_q1[0].checked || document.form1.answer_q1[1].checked || document.form1.answer_q1[2].checked) ||
         !(document.form1.answer_q2[0].checked || document.form1.answer_q2[1].checked || document.form1.answer_q2[2].checked) ||
         !(document.form1.answer_q3[0].checked || document.form1.answer_q3[1].checked || document.form1.answer_q3[2].checked) ||
          ((Ptg.trim(document.form1.answer_sub.value) === '') || !Ptg.isNumeric(document.form1.answer_sub.value)) ) {
        isValid = false;
    } else {
        isValid = true;
    }

    return isValid;
};

Ptg.miniQuizSubmit = function () {
    if ( Ptg.checkMiniQuizAnswersValidity() ) {
        var params = '';

        if ( document.form1.answer_q1[0].checked ) {
            params += 'a1(1)';
        } else if ( document.form1.answer_q1[1].checked ) {
            params += 'a1(2)';
        } else {
            params += 'a1(3)';
        }

        if ( document.form1.answer_q2[0].checked ) {
            params += 'a2(1)';
        } else if ( document.form1.answer_q2[1].checked ) {
            params += 'a2(2)';
        } else {
            params += 'a2(3)';
        }

        if ( document.form1.answer_q3[0].checked ) {
            params += 'a3(1)';
        } else if ( document.form1.answer_q3[1].checked ) {
            params += 'a3(2)';
        } else {
            params += 'a3(3)';
        }

        params += 'as(' + document.form1.answer_sub.value + ')';

        document.location.href = document.location.href + params;
    }
};

Ptg.quizAddChance = function (chances) {
	$('quiz_chances').value = parseInt($('quiz_chances').value) + chances;
	$('quizNbChances').innerHTML = $('quiz_chances').value;
}

Ptg.quizSelectCoreg = function (id) {
	$('coreg_' + id).checked = true;
	(new Effect.toggle($('coregBox_' + id)));
	(new Effect.toggle($('coregBoxValid_' + id)));
	(new Effect.toggle($('coregPoints_' + id)));
	(new Effect.toggle($('coregPointsValid_' + id)));
	Ptg.quizAddChance(1);
}

Ptg.quizSelectTellit = function (id, idx) {
	var firstname = $F('tellit_firstname_' + idx);
	var email = $F('tellit_email_' + idx);
	if ((Ptg.trim(firstname) != '') && Ptg.CheckEmail(email)) {
		var valid = false;

	    (new Ajax.Request('/ajax/checkTellit.php', {
	        method: 'post',
	        parameters: {id: id, firstname: firstname, email: email},
	        asynchronous: true
	    }));

		(new Effect.toggle($('tellitBox_' + idx)));
		(new Effect.toggle($('tellitBoxValid_' + idx)));
		(new Effect.toggle($('tellitPoints_' + idx)));
		(new Effect.toggle($('tellitPointsValid_' + idx)));
		Ptg.quizAddChance(1);
	}
}

Ptg.quizAnswerQuestion = function (id, idx) {
	var answer = $RF('form1', 'answer_q' + idx);
	if (answer > 0) {
		var valid = false;

	    (new Ajax.Request('/ajax/checkQuestionAnswer.php', {
	        method: 'post',
	        parameters: {id: id, answer: answer},
	        asynchronous: false,
	        onSuccess: function (transport) {
	        	valid = transport.responseText.evalJSON().valid;
	        }
	    }));

		(new Effect.toggle($('questionBox_' + idx)));		
		if (valid) {
			(new Effect.toggle($('questionBoxValid_' + idx)));		
			(new Effect.toggle($('questionPoints_' + idx)));
			(new Effect.toggle($('questionPointsValid_' + idx)));
			Ptg.quizAddChance(1);
		} else {
			(new Effect.toggle($('questionBoxInvalid_' + idx)));		
		}
	}
}

Ptg.quizCheckAnswersValidity = function () {
	return (parseInt($('quiz_chances').value) > 0);
};

Ptg.quizCheckAnswerSubValidity = function () {
    var as = $('form1').getInputs('text', 'answer_sub[]');
    var valid = true;
    as.each(function(e) {
		if ((Ptg.trim(e.value) === '') || !Ptg.isNumeric(e.value)) {
			valid = false;
			return;
		}
	});
    return valid;
};

Ptg.quizSubmit = function (answerSub) {
	if (answerSub) {
		if (Ptg.quizCheckAnswerSubValidity()) {
			return true;
		}
		if ($('quiz_error')) {
			$('quiz_error').style.display = 'block'
		}
		return false;
	} else if ( Ptg.quizCheckAnswersValidity() ) {
        var params = '';

        var i = 1;
        var val = true;
        while (val !== false) {
        	val = $RF('form1', 'answer_q' + i);
        	if (val) {
	        	params += 'a' + i + '(' + val + ')';
        	}
        	i++;
        }

        var c = '';
        var coregs = $('form1').getInputs('checkbox', 'coreg[]');
        coregs.each(function(e) {
			if (e.checked) {
				if (c != '') {
					c += ',';
				}
				c += e.value;
			}
		});

        if (c != '') {
        	params += 'c(' + c + ')';
        }

        var url = unescape(document.location.href);
        if (url.slice(-4) == 'q(1)') {
        	url = url.slice(0, -4);
        }
        if (url.slice(-1) != '/') {
        	url = url.slice(0, -1) + '/';
        }
        document.location.href = url + 'q(2)' + params;
    }
};

/******************************************* COOKIES *******************************************/
Ptg.ptgWriteCookie = function (name, value) {
	var argv=Ptg.ptgWriteCookie.arguments;
	var argc=Ptg.ptgWriteCookie.arguments.length;
	var expires=(argc > 2) ? new Date(argv[2]) : null;
	var path=(argc > 3) ? argv[3] : null;
	var domain=(argc > 4) ? argv[4] : null;
	var secure=(argc > 5) ? argv[5] : false;
	document.cookie=name+"="+escape(value)+
	((expires===null) ? "" : ("; expires="+expires.toGMTString()))+
	((path===null) ? "" : ("; path="+path))+
	((domain===null) ? "" : ("; domain="+domain))+
	((secure===true) ? "; secure" : "");
};

Ptg.ptgGetCookieVal = function (offset) {
	var endstr=document.cookie.indexOf (";", offset);
	if (endstr==-1) {
		endstr=document.cookie.length;
	}
	return unescape(document.cookie.substring(offset, endstr));
};

Ptg.ptgReadCookie = function (name) {
	var arg=name+"=";
	var alen=arg.length;
	var clen=document.cookie.length;
	var i=0;
	while (i<clen) {
		var j=i+alen;
		if (document.cookie.substring(i, j)==arg) {
			return Ptg.ptgGetCookieVal(j);
		}
		i=document.cookie.indexOf(" ",i)+1;
		if (i===0) {
			break;
		}
	}
	return null;
};

Ptg.ptgEraseCookie = function (name) {
	date=new Date();
	date.setFullYear(date.getFullYear()-1);
	Ptg.ptgWriteCookie(name,null,date);
};

/******************************************* WIDGETS *******************************************/
Ptg.changeStatus = function (widgetId, status) {
    var errorMsg = '';
    (new Ajax.Request('/ajax/saveWidgetStatus.php', {
        method:'post',
        parameters: {widgetId: widgetId, status: status},
        asynchronous:false,
        onSuccess: function(transport){
            errorMsg = transport.responseText || '';
        },
        onFailure: function(){
            errorMsg = '404';
        }
    }));
    return errorMsg;
};

Ptg.getRadioValue = function (radioObj) {
	var radioLength = radioObj.length;
	if(radioLength === undefined) {
		if(radioObj.checked) {
			return radioObj.value;
		} else {
			return '';
		}
	}
	for(var i = 0; i < radioLength; i++) {
		if(radioObj[i].checked) {
			return radioObj[i].value;
		}
	}
	return '';
};

Ptg.getCheckBoxesValue = function (CheckObj, prefix, startnr) {
	var CheckLength = CheckObj.length;
	var url='';
	if (CheckLength === undefined) {
		return '';
	}

	selectOne = false;

	for (var i = 0; i< CheckLength; i++) {
			url = url + prefix + (startnr++) + '(' + (CheckObj[i].checked?'1':'0') + ')';
			if (prefix==='' && CheckObj[i].checked) {
				selectOne=true;
				break;
			}
	}

	if (prefix === '') {
		return selectOne;
	}

	return url;
};

Ptg.Setting = function (setting, settingname) {
	(new Ajax.Request(
		'/ajax/settings.php',
		{method: 'get', parameters: 'setting=' + settingname + '&value=' + setting}
	));
};

Ptg.pageWidth = function () {
	return window.innerWidth != null? window.innerWidth : document.documentElement && document.documentElement.clientWidth ? document.documentElement.clientWidth : document.body !== null ? document.body.clientWidth : null;
};
Ptg.pageHeight = function () {
	return window.innerHeight != null? window.innerHeight : document.documentElement && document.documentElement.clientHeight ? document.documentElement.clientHeight : document.body !== null? document.body.clientHeight : null;
};

Ptg.show = function (tpl, id) {
	//show the window overlay
	if (!$('ptgOverlay')) {
		Ptg.overlay = new Element('div', {'id': 'ptgOverlay', 'style': 'display: none'});
		Ptg.overlay.addClassName('shopOverlay');
		$(document.body).insert(Ptg.overlay);
	} else {
		Ptg.overlay = $('ptgOverlay');
	}
	(new Effect.Appear(Ptg.overlay, {to: 0.6}));

    (new Ajax.Request('/ajax/getTemplate.php', {
        method:'post',
        parameters: {tpl: tpl, id: id},
        asynchronous:false,
        onSuccess: function(response){
			var r = response.responseText.evalJSON();

			if (!$('ptgWindow')) {
				Ptg.window = new Element('div', {'id': 'ptgWindow', 'style': 'z-index: 100; display: none; position: fixed !important; position: absolute;'});
				$(document.body).insert(Ptg.window);
			} else {
				Ptg.window = $('ptgWindow');
			}

			Ptg.window.innerHTML = r.body || '';

			//center window
			var dim = Ptg.window.getDimensions();

			Ptg.window.style.top = Math.ceil(Ptg.pageHeight() - dim.height) / 2 + 'px';
			Ptg.window.style.left = Math.ceil(Ptg.pageWidth() - dim.width) / 2 + 'px';

			Effect.Appear(Ptg.window);
        }
    }));	
};

Ptg.print = function (tpl, id) {
    (new Ajax.Request('/ajax/getTemplate.php', {
        method:'post',
        parameters: {tpl: tpl, id: id, params: 'print'},
        asynchronous:false,
        onSuccess: function(response){
			var r = response.responseText.evalJSON();
			if (!$('printFrame')) {
				var iframe = new Element('iframe', {
					name: 'printFrame',
					id: 'printFrame',
					style: 'position: absolute; left: -50px; width: 1px; height: 1px;'
				});
				document.body.appendChild(iframe);
			}
			window.printFrame.document.title = r.title;
			window.printFrame.document.body.innerHTML = r.body || '';
			window.printFrame.focus();
			window.printFrame.print();
        }
    }));
};

Ptg.showBox = function (id, elmClass) {
	var box = $(id);

	if (box) {
		if (!box.visible()) {
			var boxes = $$(elmClass);

			boxes.each(function(e) {
				if (e.visible()) {
					Effect.BlindUp(e);
				}
			});
		}

		(new Effect.toggle(box, 'blind'));
	}
};

Ptg.removeChildRecurs = function (el) {
    while(el.childNodes.length > 0) {
    	Ptg.removeChildRecurs(el.childNodes[el.childNodes.length - 1]);
    }
    el.parentNode.removeChild(el);
};

Ptg.deleteAction = function (id, game) {
    (new Ajax.Request('/ajax/deleteAction.php', {
        method: 'post',
        parameters: {id: id, game: game},
        onSuccess: function (transport) {
        	valid = transport.responseText.evalJSON().valid;
        	if (valid) {
        		Ptg.removeChildRecurs($('myAction_' + id));
        		Ptg.removeChildRecurs($('myAction2_' + id));
        	}
        }
    }));
};

Ptg.doQodAction = function (idx, id, game) {
	var answer = 0;
	if ($('answer_1_chk').checked) {
		answer = 1;
	} else if ($('answer_2_chk').checked) {
		answer = 2;
	} else if ($('answer_3_chk').checked) {
		answer = 3;
	}

	if (answer > 0) {
	    (new Ajax.Request('/ajax/doQodAction.php', {
	        method: 'post',
	        parameters: {id: id, answer: answer, game: game, idx: idx},
	        onSuccess: function (transport) {
	        	response = transport.responseText.evalJSON();
	        	if (response.valid) {
	        		if (response.id) {
	        			//insert a new question
	        			if (response.gotCredits) {
	        				$('act_qod_ok_close').hide();
	        				$('act_qod_ok_next').show();
	        				$('act_qod_ok').show();
	    	    			Ptg.updateCredits();
	        			} else {
	        				$('act_qod_not_ok_close').hide();
	        				$('act_qod_not_ok_next').show();
	        				$('act_qod_not_ok').show();
	        			}
		        		$('act_qod_question').innerHTML = response.question;
		        		$('answer_1').innerHTML = response.answer1;
		        		$('answer_2').innerHTML = response.answer2;
		        		$('answer_3').innerHTML = response.answer3;
		        		$('answer_1_chk').checked = false;
		        		$('answer_2_chk').checked = false;
		        		$('answer_3_chk').checked = false;
		        		$('unfold_l1').attributes.qod_url.value = response.url;
		        		$('qod_id').attributes.qod_id.value = response.id;
		        		$('unfold_q1').hide();
		        		$('unfold_l1').show();
		        		$('act_qod_params').attributes.params.value = response.params;
		        		var elm = $('act_qod_params_line_' + idx);
		        		if (elm) {
		        			elm.attributes.params.value = response.params;
		        		}
	        		} else {
	        			//remove the action
	        			Ptg.removeAction(idx, true);
	        			if (response.gotCredits) {
	        				$('act_qod_ok_next').hide();
	        				$('act_qod_ok_close').show();
	        				$('act_qod_ok').show();
	    	    			Ptg.updateCredits();
	        			} else {
	        				$('act_qod_not_ok_next').hide();
	        				$('act_qod_not_ok_close').show();
	        				$('act_qod_not_ok').show();
	        			}
	        		}
	        	}
	        }
	    }));
	}
};

Ptg.doCoregAction = function (idCoreg) {
    (new Ajax.Request('/ajax/doCoregAction.php', {
        method: 'post',
        parameters: {id: idCoreg},
        onSuccess: function (transport) {
        	valid = transport.responseText.evalJSON().valid;
        	if (valid) {
        		var el_line = $('coregAction_line_' + idCoreg);
        		if (el_line) {
        			Ptg.removeChildRecurs(el_line);
        		}

    			Ptg.removeAction('coregAction_' + idCoreg, true);
    			Ptg.updateCredits();
        	}
        }
    }));
};

Ptg.doAction = function (url, directClick, actionId) {
	if (url != '') {
		window.open(url);
		if (directClick) {
			Ptg.removeAction(actionId, true);
			Ptg.updateCredits();
		} else {
			var elm = undefined;
			if (elm = $('action_status_' + actionId)) $('action_status_' + actionId).show();
			if (elm = $('action_legend2_' + actionId)) $('action_legend2_' + actionId).hide();
			if (elm = $('actionL_legend_' + actionId)) $('actionL_legend_' + actionId).hide();
			if (elm = $('actionL_legend2_' + actionId)) $('actionL_legend2_' + actionId).hide();
			if (elm = $('action_status2_' + actionId)) $('action_status2_' + actionId).show();
			if (elm = $('actionL_status_' + actionId)) $('actionL_status_' + actionId).show();
			if (elm = $('actionL_status2_' + actionId)) $('actionL_status2_' + actionId).show();
		};
	}
};

Ptg.showMoreGiftsWhl = function () {
	(new Effect.toggle($('kdoJck_hidden'), 'blind'));
	$('btn_showMoreGifts').hide();
};

Ptg.closedActionPopup = function () {
	//reload action popup if the user has 0 credits
	Ptg.$.get('protocol/credits.php', function(data) {
		if (data.match(/^EMAIL=.{3,}?&CR=0$/i)) {
			setTimeout(Ptg.showMoreActions, 400);
		}
	});
};

Ptg.showMoreActions = function () {
	if (typeof v55 != "undefined") {
		Ptg.$.simplewindow.settings.useFlashFix = true;
		Ptg.$.simplewindow.settings.opacity = 0.0;
		Ptg.$.simplewindow({iframe: '/modules/index.php?from=' + v55_game, iframeWidth: 600, iframeHeight: 350}, 'action_popup');
		Ptg.$(document).unbind('afterClose.simplewindow', Ptg.closedActionPopup).bind('afterClose.simplewindow', Ptg.closedActionPopup); 
	} else {
		Ptg.showActions('#action_star2 .boxListAction', 'action_star2');
		Ptg.showActions('#action_inscr3 .boxListAction', 'action_inscr3');
		Ptg.showActions('#action_buy3 .boxListAction', 'action_buy3');
		Ptg.showActions('#action_click3 .boxListAction', 'action_click3');

		if ($('btn_more_star')) {
			$('btn_more_star').style.display = 'none';
		}
		if ($('btn_more_inscr')) {
			$('btn_more_inscr').style.display = 'none';
		}
		if ($('btn_more_buy')) {
			$('btn_more_buy').style.display = 'none';
		}
		if ($('btn_more_click')) {
			$('btn_more_click').style.display = 'none';
		}
		if ($('action_star')) {
			(new Effect.toggle($('action_star'), 'blind'));
		}
		if ($('action_inscr')) {
			(new Effect.toggle($('action_inscr'), 'blind'));
		}
		if ($('action_buy')) {
			(new Effect.toggle($('action_buy'), 'blind'));
		}
		if ($('action_click')) {
			(new Effect.toggle($('action_click'), 'blind'));
		}
	}
};

Ptg.showActions = function (elmGroup, divId) {
	var actions = $$(elmGroup);

	actions.each(function(e) {
		e.style.display = 'block';
	});

	var elm = $(divId);
	if (elm) {
		(new Effect.toggle(elm, 'blind'));
	}
};

Ptg.RemoveActionLine = function (id) {
	var el_line = $('action_line_' + id);
	if (el_line) {
		Ptg.removeChildRecurs(el_line);
	}
	var el_line2 = $('action_line2_' + id);
	if (el_line2) {
		Ptg.removeChildRecurs(el_line2);
	}
};

Ptg.removeAction = function (id, bDelete) {
	var action = $('action_' + id) || $(id);
	var actionParentId = action.parentNode.id;
	if (bDelete) {
		Ptg.removeChildRecurs(action);
		Ptg.RemoveActionLine((id.replace ? id.replace(/\D/g, '') : id));
	}

	switch (actionParentId) {
	case 'action_inscr':
		var actions = $$('#action_inscr2 .boxListAction');
		if (actions[0]) {
			$(actionParentId).insert(actions[0]);
		}
		break;
	case 'action_inscr2':
		break;
	case 'action_buy':
		var actions = $$('#action_buy2 .boxListAction');
		if (actions[0]) {
			$(actionParentId).insert(actions[0]);
		}
		break;
	case 'action_buy2':
		break;
	case 'action_click':
		var actions = $$('#action_click2 .boxListAction');
		if (actions[0]) {
			$(actionParentId).insert(actions[0]);
		}
		break;
	case 'action_click2':
		break;
	default: // = widget
		var actionsInscr = $$('#action_inscr .boxListAction');
		var actionsInscr3 = $$('#action_inscr3 .line_action');
		var actionsBuy = $$('#action_buy .boxListAction');
		var actionsBuy3 = $$('#action_buy3 .line_action');
		var actionsClick = $$('#action_click .boxListAction');
		var actionsClick3 = $$('#action_click3 .line_action');
		var idx = 0;
		var currentId = 0;
		while (actionsInscr[idx] || actionsBuy[idx] || actionsClick[idx]) {
			if (actionsInscr[idx] && actionsBuy[idx]) {
				if (actionsInscr[idx].id.replace(/\D/g, '') < actionsBuy[idx].id.replace(/\D/g, '')) {
					currentId = actionsInscr[idx].id.replace(/\D/g, '');
					if (!$('action_status_' + currentId).visible()) {
						Ptg.removeAction(actionsInscr[idx].id, false);
						$(actionParentId).insert(actionsInscr[idx]);
						if (actionParentId == 'action_star') { 
							$('action_star2').insert(actionsInscr3[idx*2+1]);
						} else if ((actionParentId == 'actionsStarjck') || (actionParentId == 'actionsStarscr') || (actionParentId == 'actionsStarwhl')) {
							Ptg.removeChildRecurs($('action_line_' + currentId));
						}
						break;
					}
				} else {
					currentId = actionsBuy[idx].id.replace(/\D/g, ''); 
					if (!$('action_status_' + currentId).visible()) {
						Ptg.removeAction(actionsBuy[idx].id, false);
						$(actionParentId).insert(actionsBuy[idx]);
						if (actionParentId == 'action_star') { 
							$('action_star2').insert(actionsBuy3[idx*2+1]);
						} else if ((actionParentId == 'actionsStarjck') || (actionParentId == 'actionsStarscr') || (actionParentId == 'actionsStarwhl')) {
							Ptg.removeChildRecurs($('action_line_' + currentId));
						}
						break;
					}
				}
			} else if (actionsInscr[idx]) {
				currentId = actionsInscr[idx].id.replace(/\D/g, '');
				if (!$('action_status_' + currentId).visible()) {
					Ptg.removeAction(actionsInscr[idx].id, false);
					$(actionParentId).insert(actionsInscr[idx]);
					if (actionParentId == 'action_star') { 
						$('action_star2').insert(actionsInscr3[idx*2+1]);
					} else if ((actionParentId == 'actionsStarjck') || (actionParentId == 'actionsStarscr') || (actionParentId == 'actionsStarwhl')) {
						Ptg.removeChildRecurs($('action_line_' + currentId));
					}
					break;
				}
			} else if (actionsBuy[idx]) {
				currentId = actionsBuy[idx].id.replace(/\D/g, ''); 
				if (!$('action_status_' + currentId).visible()) {
					Ptg.removeAction(actionsBuy[idx].id, false);
					$(actionParentId).insert(actionsBuy[idx]);
					if (actionParentId == 'action_star') { 
						$('action_star2').insert(actionsBuy3[idx*2+1]);
					} else if ((actionParentId == 'actionsStarjck') || (actionParentId == 'actionsStarscr') || (actionParentId == 'actionsStarwhl')) {
						Ptg.removeChildRecurs($('action_line_' + currentId));
					}
					break;
				}
			} else {
				currentId = actionsClick[idx].id.replace(/\D/g, ''); 
				if (!$('action_status_' + currentId).visible()) {
					Ptg.removeAction(actionsClick[idx].id, false);
					$(actionParentId).insert(actionsClick[idx]);
					if (actionParentId == 'action_star') { 
						$('action_star2').insert(actionsClick3[idx*2+1]);
					} else if ((actionParentId == 'actionsStarjck') || (actionParentId == 'actionsStarscr') || (actionParentId == 'actionsStarwhl')) {
						Ptg.removeChildRecurs($('action_line_' + currentId));
					}
					break;
				}
			}
			idx++;
		}
	}
};

Ptg.removeActionById = function (id) {
	var boxes = $$('.boxListAction');

	boxes.each(function(e) {
		if (e.readAttribute('value') == id) {
			Ptg.removeAction(e.id, true);
			throw $break;
		}
	});
};

Ptg.showModalDialog = function (tpl, params) {
	//insert dialog overlay, create it if it doesnt exists
	var overlay;
	if (!$('dialogOverlay')) {
		overlay = new Element('div', {'id': 'dialogOverlay', 'style': 'display: none'});
		overlay.addClassName('dialogOverlay');
		$(document.body).insert(overlay);
	} else {
		overlay = $('dialogOverlay');
	}

	//insert dialog content, create it if it doesnt exists
	var content;
	if (!$('dialogContent')) {
		content = new Element('div', {'id': 'dialogContent', 'style': 'display: none;'});
		content.addClassName('dialogContent');
		$(document.body).insert(content);
	} else {
		content = $('dialogContent');
	}

	//clear the dialog content
	content.innerHTML = '';

	var p = {tpl: tpl};
	if (typeof params != "undefined") {
		for (attrname in params) {
			p[attrname] = params[attrname];
		}
	}

	//make an ajax call to get the template
    (new Ajax.Request('/ajax/getTemplate.php', {
        method:'post',
        parameters: p,
        asynchronous:false,
        onSuccess: function(response){
        	//scroll the page to the top if the user use IE6-, because there is no position: fixed in IE6-
        	var appVer = navigator.appVersion.toLowerCase();
        	var iePos = appVer.indexOf('msie');
        	if (iePos != -1) {
        		is_minor = parseFloat(appVer.substring(iePos + 5, appVer.indexOf(';', iePos)));
        		if (parseInt(is_minor, 10) <= 6) {
        			window.scroll(0);
        		}
        	}

        	//read the response
			var r = response.responseText.evalJSON();
			content.innerHTML = r.body;

			//hide a bunch of objects that appear in front of the div overlay
			$$('object', 'embed', 'iframe').each(function(node){ node.style.visibility = 'hidden'; });

			//center the dialog
			var dim = {
				width: parseInt($('modalContent').style.width, 10),
				height: parseInt($('modalContent').style.height, 10)
			}

			content.style.width = (dim.width + 12 + 20) + 'px';
			content.style.height = (dim.height + 50) + 'px';

			content.style.marginLeft = (-dim.width * 0.5) + 'px';
			content.style.marginTop = (-dim.height * 0.5) + 'px';

			$('modalContentLeft').style.height = (dim.height - 10) + 'px';
			$('modalContentRight').style.height = $('modalContentLeft').style.height;
			//show the dialog
			Effect.Appear(overlay, {to: 0.6});
			Effect.Appear(content, {to: 1.0});
        }
    }));
};

Ptg.hideModalDialog = function () {
	Effect.Fade($('dialogContent'));
	Effect.Fade($('dialogOverlay'), {'afterFinish': function() { $$('object', 'embed', 'iframe').each(function(node){ node.style.visibility = 'visible'; }); }});
};

Ptg.updateCredits = function () {
	var flash;
	if (Prototype.Browser.IE) {
		flash = $("ie_myPTGFlashGame");
	} else {
		flash = $("myPTGFlashGame");
	}
	if (flash) {
		flash.reload_credit();
	}
	
	var fid_points_actions = $('fid_points_actions');
	if (fid_points_actions) {
	    (new Ajax.Request('/ajax/getActionsCredits.php', {
	        method:'post',
	        onSuccess: function(transport){
	    		fid_points_actions.innerHTML = transport.responseText.evalJSON().credits;
	    	}
	    }));
	}
};

Ptg.toggleAccountBox = function (boxId, img) {
	var box = $('box_' + boxId);
	if (box.visible()) {
		if (img) {
			img.src = img.attributes.srcclosed.value;
		}
		new Effect.BlindUp(box, {
			queue: { position: 'end', scope: 'box_' + boxId, limit: 1 },
			afterFinish: function () {
				if ($('box_boto_' + boxId)) {
					$('box_boto_' + boxId).hide();
				}
				if ($('box_botc_' + boxId)) {
					$('box_botc_' + boxId).show();
				}
			}
		});
	} else {
		if (img) {
			img.src = img.attributes.srcopen.value;
		}
		if ($('box_botc_' + boxId)) {
			$('box_botc_' + boxId).hide();
		}
		if ($('box_boto_' + boxId)) {
			$('box_boto_' + boxId).show();
		}
		new Effect.BlindDown(box, {
			queue: { position: 'end', scope: 'box_' + boxId, limit: 1 }
		});
	}
};

Ptg.toggleBox = function (boxId, img) {
	var box = $(boxId);
	if (box.visible()) {
		if (img) {
			img.src = img.attributes.srcclosed.value;
		}
	} else {
		if (img) {
			img.src = img.attributes.srcopen.value;
		}
	}
	(new Effect.toggle(box, 'Blind'));
};

/*
Ptg.myBlankUrl = function (url){
	alert('test');
	var newWindow = window.open(url, '_blank');
	newWindow.focus();
	return false;
}*/

Ptg.HideGifts = function (idElem) {
	if (typeof v55 != "undefined") {
		Ptg.showMoreActions();
	} else {
		new Effect.BlindUp($(idElem), {});
		$('GameMaximize').show();
		$('GameMinimize').hide();
		Ptg.changeStatus('','max');
		Ptg.showMoreActions();
		document.location.hash = "#actions";
	}
}

Ptg.PostCoreg = function (id, mod, game, elmId) {
	(new Ajax.Request('/ajax/doCoregAction.php', {
		method: 'post',
		parameters: {id: id, mod: mod, game: game},
		onSuccess: function (transport) {
			valid = transport.responseText.evalJSON().valid;
			if (valid && $(elmId)) {
				Ptg.removeChildRecurs($(elmId));
			}
		}
	}));
}

Ptg.Autocompleter = Class.create(Autocompleter.Base, {
	initialize: function(element, update, url, options) {
		this.baseInitialize(element, update, options);
		this.options.asynchronous  = true;
		this.options.onComplete    = this.onComplete.bind(this);
		this.options.defaultParams = this.options.parameters || null;
		this.url                   = url;
		this.cache				   = new Array();
		this.keyword			   = '';
	},

	generateHtml: function() {
		var value = this.getToken();
		var highlight;
		
		var html = '<ul>';
		var i = 0;
		this.cache.each(function(gift) {
			var highlight = gift.replace(new RegExp("(" + value + ")", "ig"), '<b>' + value + '</b>');
			if (highlight != gift) {
				if (i++ == 9) {
					throw $break;
				}
				html += '<li>' + highlight + '</li>';
			}
		});
		//html += '<li class="last">masquer les suggestion <img src="/style/default/1024/img/pages/ico/bt_close_alerte_blanc.png"></li>'
		html += '</ul>';
		html += '<div class="top_autocomplete"></div><div class="bot_autocomplete"></div>';
		if (i > 0) {
			this.updateChoices(html);
		} else {
			this.updateChoices('');
		}
	},

	getUpdatedChoices: function() {
		if (!(/msie|MSIE 6/.test(navigator.userAgent))) {
			var value = this.getToken();
	
			if ((value.length > 0) && (((value.length < 3 ) && (value != this.keyword)) || (this.keyword == ''))) { // must reload cache
				this.keyword = value;
	
				var entry = encodeURIComponent(this.options.paramName) + '=' + encodeURIComponent(value);
	
				this.options.parameters = this.options.callback ? this.options.callback(this.element, entry) : entry;
	
				if (this.options.defaultParams) { 
					this.options.parameters += '&' + this.options.defaultParams;
				}
	
				new Ajax.Request(this.url, this.options);
			} else {
				this.generateHtml();
			}
		}
	},

	onComplete: function(request) {
		this.cache = request.responseText.evalJSON();
		this.generateHtml();
	}
});

var Rotator = Class.create({
	initialize: function (id) {
		this.id = id;
		this.elmsTab = $$('.' + this.id + 'Tab');
		this.elmsBody = $$('.' + this.id + 'Body');
		this.timeoutId = 0;
		this.timeoutStepId = 0;
		this.currentStep = 0;

		var self = this; 
		this.elmsTab.each(function (elmTab) {
			elmTab.observe('mouseover', function () { self.mouseOver(this); });
			elmTab.observe('mouseout', function () { self.mouseOut(); });
		});

		this.step();
	},

	step: function (setTimeOut) {
		if (typeof(setTimeOut) == 'undefined') {
			setTimeOut = true;
		}

		var self = this;
		if (this.elmsTab[this.currentStep] && this.elmsBody[this.currentStep]) {
			this.elmsBody.each(function (elmBody) {
				if (elmBody == self.elmsBody[self.currentStep]) {
					elmBody.appear({ duration: 0.5 });
				} else if (elmBody.visible()) {
					elmBody.fade({ duration: 0.5 });
				}
			});
			this.elmsTab.each(function (elmTab) {
				if (elmTab == self.elmsTab[self.currentStep]) {
					elmTab.addClassName(self.id + 'TabActive');
				} else {
					elmTab.removeClassName(self.id + 'TabActive');
				}
			});

			if (setTimeOut) {
				this.currentStep++;
				this.timeoutId = setTimeout(function () { self.step(); }, 5000);
			}
		} else if (this.currentStep > 0) {
			this.currentStep = 0;
			this.step();
		}
	},

	mouseOver: function (elm) {
		if (this.timeoutId > 0) {
			clearTimeout(this.timeoutId);
			this.timeoutId = 0;
		}
		if (this.timeoutStepId > 0) {
			clearTimeout(this.timeoutStepId);
			this.timeoutStepId = 0;
		}
		for (var i = 0, len = this.elmsTab.length; i < len; ++i) {
			if (this.elmsTab[i] == elm) {
				this.currentStep = i;
				var self = this;
				this.timeoutStepId = setTimeout(function () { self.step(false); }, 250);
				break;
			}
		}
	},

	mouseOut: function () {
		if (this.timeoutStepId > 0) {
			clearTimeout(this.timeoutStepId);
			this.timeoutStepId = 0;
		}
		if (this.timeoutId == 0) {
			this.currentStep++;
			var self = this;
			this.timeoutId = setTimeout(function () { self.step(); }, 5000);
		}
	}
});

var GiftsHorizontalSlideShow = Class.create({
	initialize: function (options) {
		this.options = options;
		this.slideShow = $(this.options.id);
		this.giftsCount = $$('#' + this.options.id + ' li').length;
		this.step();
	},

	step: function () {
		var gifts = $$('#' + this.options.id + ' li');
		if (gifts.length > 4) {
			var elm = Element.remove(gifts[0]);
			gifts[this.giftsCount - 1].insert({after: elm});
			this.slideShow.style.left = 0;

			var self = this;
			new Effect.Move(
				this.slideShow,
			{
				x: this.options.offset,
				afterFinish: function () {
					self.step();
				},
				duration: 5,
				transition: Effect.Transitions.linear
			});
		}
	}
});
var GiftsVerticalSlideShow = Class.create({
	initialize: function (options) {
		this.options = options;
		this.slideShow = $(this.options.id);
		this.giftsCount = $$('#' + this.options.id + ' li').length;
		this.step();
	},

	step: function () {
		var gifts = $$('#' + this.options.id + ' li');
		if (gifts.length > 4) {
			var elm = Element.remove(gifts[0]);
			gifts[this.giftsCount - 1].insert({after: elm});
			this.slideShow.style.top = 0;

			var self = this;
			new Effect.Move(
				this.slideShow,
			{
				y: this.options.offset,
				afterFinish: function () {
					self.step();
				},
				duration: 5,
				transition: Effect.Transitions.linear
			});
		}
	}
});

var GiftsSlideShow = Class.create({
	initialize: function (options) {
		this.options = options;
		this.giftsCount = this.options.images.length;
		this.currentGiftIdx = 0;

		if (this.giftsCount > 1) {
			this.preloadNextGift();

			var self = this;
			setTimeout(function () { self.step(); }, this.options.duration);
		}
	},

	getNextIdx: function () {
		var nextIdx = this.currentGiftIdx + 1;
		if (nextIdx == this.giftsCount) nextIdx = 0;
		return nextIdx;
	},

	preloadNextGift: function () {
		var nextIdx = this.getNextIdx()
		if ($(this.options.idImagePrefix + nextIdx)) return;

		var o = {
			src: this.options.images[nextIdx],
			id: this.options.idImagePrefix + nextIdx,
			alt: ''
		};
		Object.extend(o, this.options.imageAttributes);

		var img = new Element('img', o);
		img.hide();
		if (this.options.idTextPrefix) {
			var txt = new Element(this.options.textElement || 'div', {
				id: this.options.idTextPrefix + nextIdx,
				'class': this.options.textClass,
				style: 'display: none'
			});
			txt.update(this.options.texts[nextIdx]);

			$(this.options.idTextPrefix + this.currentGiftIdx).insert({after: txt});
		}
		$(this.options.idImagePrefix + this.currentGiftIdx).insert({after: img});
	},

	step: function () {
		var nextIdx = this.getNextIdx()

		$(this.options.idImagePrefix + nextIdx).appear({ duration: this.options.fadeDuration });
		$(this.options.idImagePrefix + this.currentGiftIdx).fade({ duration: this.options.fadeDuration });
		if (this.options.idTextPrefix) {
			$(this.options.idTextPrefix + nextIdx).appear({ duration: this.options.fadeDuration });
			$(this.options.idTextPrefix + this.currentGiftIdx).fade({ duration: this.options.fadeDuration });
		}

		this.currentGiftIdx = nextIdx;

		this.preloadNextGift();

		var self = this;
		setTimeout(function () { self.step(); }, this.options.duration);
	}
});
