﻿/*
 * Functions to open and hide popup divs
 */
function openPopup(type, header, text, onconfirm, opt_confirmtext, opt_declinetext, opt_redborder) 
{
	if (type == 'div_confirm_delete_team') {
		$('lp_popup_custom').style.display = 'block';
	}
	else {
		if (type == 'confirm') {
			if (onconfirm != undefined) 
				$('lp_popup_confirm').onclick = function(){
					eval(onconfirm);
				};
			$('lp_popup_content').style.borderColor = '#cc0000';
			$('lp_popup_close').style.backgroundColor = "white";
			$('lp_popup_close').style.color = "#3399cc";
			$('lp_popup_close').style.textDecoration = "underline";
			$('lp_popup_close').style.border = "0";
			$('lp_popup_close').style.marginLeft = "20px";
			$('lp_popup_confirm').style.display = '';
		}
        
        else if (type == 'custom_texts_confirm') 
        {
			if (onconfirm != undefined) 
				$('lp_popup_confirm').onclick = function(){
					eval(onconfirm);
				};
			$('lp_popup_content').style.borderColor = '#01c513';
			$('lp_popup_close').style.backgroundColor = "white";
			$('lp_popup_close').style.color = "#3399cc";
			$('lp_popup_close').style.textDecoration = "underline";
			$('lp_popup_close').style.border = "0";
			$('lp_popup_close').style.marginLeft = "20px";
			$('lp_popup_confirm').style.display = '';
            if (opt_confirmtext != undefined)
            {
                $('lp_popup_confirm').value = opt_confirmtext;   
            }
            
            if (opt_declinetext != undefined)
            {
                $('lp_popup_close').value = opt_declinetext;   
            }
            
            if (opt_redborder != undefined)
            {
                $('lp_popup_content').style.borderColor = '#cc0000';    
            }
                
        }
		else {
            
            if (type == 'notification_red')
            {
                $('lp_popup_content').style.borderColor = '#cc0000';
            }
            
			if (onconfirm != undefined) 
				$('lp_popup_close').onclick = function(){
					eval(onconfirm);
				};            
            
			$('lp_popup_confirm').style.display = 'none';
			$('lp_popup_close').value = 'OK';
		}
		if (header != undefined) 
			$('lp_popup_header').innerHTML = header;
		if (text != undefined) 
			$('lp_popup_text').innerHTML = text;
		$('lp_popup').style.display = 'block';
	}
	fadeInBackground();
}

function getDocHeight() {
	var D = document;
	return Math.max(Math.max(D.body.scrollHeight, D.documentElement.scrollHeight), Math.max(D.body.offsetHeight, D.documentElement.offsetHeight), Math.max(D.body.clientHeight, D.documentElement.clientHeight));
}
function getDocWidth() {
	var D = document;
	return Math.max(Math.max(D.body.scrollWidth, D.documentElement.scrollWidth), Math.max(D.body.offsetWidth, D.documentElement.offsetWidth), Math.max(D.body.clientWidth, D.documentElement.clientWidth));
}

function closePopup() {
	fadeOutBackground();
    $('lp_popup').style.display = 'none';
}

function setOpacity(div_id, value) {
	$(div_id).style.filter = 'alpha(opacity=' + (value * 10) + ')';
	$(div_id).style.opacity = value / 10;
	$(div_id).style.MozOpacity = value / 10;
}

// Fade in the background
// Skip the fading for ie6
function fadeInBackground() {
//	isIE6 = /msie|MSIE 6/.test(navigator.userAgent);
//	if (!isIE6) {
		setOpacity('lp_popup_background',0);
		$('lp_popup_background').style.height = getDocHeight()+'px';
		$('lp_popup_background').style.width = getDocWidth()+'px';
		$('lp_popup_background').style.display = 'block';
		for (var i = 0; i <= 50; i++) {
			setTimeout('setOpacity(\'lp_popup_background\',' + (i / 10) + ')', 8 * i);
		}
//	}
//	else {
//		setOpacity(5);
//		$('lp_popup_background').style.height = getDocHeight()+'px';
//		$('lp_popup_background').style.display = 'block';
//	}
}

// Fade out the background
// Skip the fading for ie6
function fadeOutBackground() {
//	isIE6 = /msie|MSIE 6/.test(navigator.userAgent);
//	if (!isIE6) {
		setTimeout("hideBackground()", 400);
		var id;
		for( var i = 50 ; i <= 100 ; i++ ) {
			setTimeout( 'setOpacity(\'lp_popup_background\',' + (10 - i / 10) + ')' , 8 * (i-50) );
		}
//	}
//	else
//	{
//		hideBackground();
//	}
}

function hideBackground() {
	setOpacity('lp_popup_background',0);
	$('lp_popup_background').style.display = 'none';
}

/*
 * Functions to show hide elements by id (eg. custom popups)
 */
function showById(nid) 
{
    $(nid).style.display = 'block';	
}

function hideById(nid)
{
    $(nid).style.display = 'none';
}

function showHideById(nid)
{
	if ($(nid).style.display == 'block' || $(nid).style.display == '')
	{
		$(nid).style.display = 'none';
	}
	else
	{
		$(nid).style.display = '';
	}
}

function hidePlayerCardById(nid)
{
	fadeOutBackground();
	$(nid).style.display = 'none';
	if ($('div_search_players'))
	{
		showById('div_search_players');
		hideById('whitearea');
	}
}

/*
 * Function to hide and show boxes when click image
 */
function hideshowDivByImg(box_div, image_div, imagepath)
{
	
	if ($(box_div).style.display == 'block' || $(box_div).style.display == '')
	{
		  $(box_div).style.display = 'none';
		  $(image_div).src = imagepath + "/toggle-arrow-down.png";
	} 
	else
	{
		  $(box_div).style.display = 'block';
		  $(image_div).src = imagepath + "/toggle-arrow-right.png";
	}	
}

/*
 * Function to limit writing characters in textarea
 */
function textCounter(field, countfield, maxlimit)
{
	if (field.value.length > maxlimit) // if too long...trim it!
		field.value = field.value.substring(0, maxlimit);
	// otherwise, update 'characters left' counter
	else 
		countfield.value = maxlimit - field.value.length;
}

/*
 * Inbox recipient field functions
 */
function updateItemList(item) 
{
	var receiver = item.innerHTML;
	var receiverId = item.id;
	if($('receiver' + receiver) == null)
	{
		$('peopleReceiverList').innerHTML = $('peopleReceiverList').innerHTML + '<li class="receiverListItem" id="receiver' + receiver + '" onclick="onClickDeleteItem(\'' + receiver + '\')">' + receiver + '</li>';
		$('hiddenReceiverList').innerHTML = $('hiddenReceiverList').innerHTML + '<input type="hidden" id="hiddenReceiver' + receiver + '" name="receiver[]" value="' + receiverId + '" />';
	}
	$('peopleReceivers').value = '';
}
	
function deleteItem(event)
{
	if(event.keyCode == 8 && $('peopleReceivers').value == '')
	{
		var container = $('peopleReceiverList');
		var hiddenContainer = $('hiddenReceiverList');
		if(container.innerHTML != '')
		{
			var containerElements = container.getElementsByTagName('li');
			var lastElement = containerElements[containerElements.length-1];
			container.removeChild(lastElement);
			if(hiddenContainer.innerHTML != '')
			{
				var hiddenContainerElements = hiddenContainer.getElementByTagName('input');
				var lastHiddenElement = hiddenContainerElements[hiddenContainerElements.length-1];
				hiddenContainer.removeChild(lastElement);	
			}
		}
	}	
}
	
function onClickDeleteItem(receiver)
{
	var receiverElement = $('receiver' + receiver);
	var hiddenReceiverElement = $('hiddenReceiver' + receiver);
		
	receiverElement.parentNode.removeChild(receiverElement);
	hiddenReceiverElement.parentNode.removeChild(hiddenReceiverElement);
}

function countTextLength(text_field_id,count_field_id,max_length)
{
	var text_length=$F(text_field_id).length;
	
	if (text_length > max_length) // if too long...trim it!
		$(text_field_id).value = $F(text_field_id).substring(0, max_length);
	// otherwise, update 'characters left' counter
	else 
		$(count_field_id).innerHTML = max_length - text_length;

}
function countDescriptionLength(description_field_id,show_field_id)
{
	var description_length=$(description_field_id).innerHTML.length;
	$(show_field_id).innerHTML=300-description_length;
	
}

/*
 * Friend invitation functions
 */
function trim(str) 
{  
	if(str.charAt(0) == " ")
	{  
		str = TrimUsingRecursion(str.substring(1));
	}
	if (str.charAt(str.length-1) == " ")
	{  
		str = TrimUsingRecursion(str.substring(0,str.length-1));
	}
	return str;
}

function validate_email(email)
{
	if(email.match(/[a-z0-9.!\#$%&\'*+-/=?^_`{|}~]+@([0-9.]+|([^\s\'"<>]+\.+[a-z]{2,6}))/))
	{
		return true;
	}
	else
	{
		return false;
	}
}

function validate_insert_email(error_empty_email, error_invalid_email)
{
	// get the the email and compare it with the mail list.
	var new_mail = trim($("new_email").value);
	var a="&#228;";
	var o="&#246;";
	if(new_mail.length < 1)
	{
		openPopup('notification', error_empty_email, '');
		return false;
	}
	else
	{
		// check the validity of the email.
		if(!validate_email(new_mail))
		{
			openPopup('notification', error_invalid_email, '');
			return false;
		}
		else
		{
			return true;
		
		}
	}
}

function check_invite_email_exists(error_duplicate_email)
{	var a="&#228;";
	var o="&#246;";
	var new_mail = trim($("new_email").value);
	// get the tbody which contains the list of emails.
	var tbody = $("email_tbody");
	var email_list = new Array();
	var return_value = new Array();
	var last_bgcolor = "#ffffff";
	//alert(tbody.childNodes.length);
	for(i=0; i<tbody.childNodes.length; i++)
	{
		var mail_tr = tbody.childNodes[i];
		if(mail_tr.nodeName.toLowerCase() == "tr")
		{
			//alert(mail.childNodes.length);
			for(j=0; j<mail_tr.childNodes.length; j++)
			{
				var mail_td = mail_tr.childNodes[j];
				if(mail_td.nodeName.toLowerCase() == "td")
				{
					for(k=0; k<mail_td.childNodes.length; k++)
					{
						var mail_label = mail_td.childNodes[k];
						if(mail_label.name == "invited_mails[]")
						{
							email_list.push(mail_label.value);
						}
						if(mail_label.value == new_mail)
						{						
							openPopup('notification', error_duplicate_email, '');
							return true;
						}
					}
				}
			}
		}
	}
	return false;
}

function change_send_invitation_button_status(button_id, tbody_id)
{
	// get the tbody.
	tbody = $(tbody_id);
	
	// set the original status to false.
	btn = 0;
	
	for(i=0; i<tbody.childNodes.length; i++)
	{
		var mail_tr = tbody.childNodes[i];
		if(mail_tr.nodeName.toLowerCase() == "tr")
		{
			// if there is at least one table row, set the status to true.
			btn = 1;
		}
	}
	if(btn==1)
	{
		$(button_id).className = "button";
		$(button_id).disabled = false;
	}
	else
	{
		$(button_id).className = "button_inactive";
		$(button_id).disabled = true;
	}
}

function delete_invite_friends(body_id,tr_id)
{
	// get the tbody and the tr which is going to be deleted.
	var tbody = $(body_id);
	var deleted_tr = $(tr_id);
	//alert(deleted_tr.nodeName);
	tbody.removeChild(deleted_tr);
	reclass_table_odd_even(body_id);
	change_send_invitation_button_status('btn_send', body_id);
	
}
function add_email_to_invite_list(type, error_empty_email, error_invalid_email, error_duplicate_email)
{
	if(validate_insert_email(error_empty_email, error_invalid_email)==true)	
	{
		var new_mail = trim($("new_email").value);
		var tbody = $("email_tbody");

		if (check_invite_email_exists(error_duplicate_email)) return 0;
		// if the email is not in the mail list, add this email to the list.
		
		// create the label of new mail
		var new_label = document.createElement('label');
		new_label.innerHTML = new_mail;
		
		var new_space = document.createElement('label');
		new_space.innerHTML = '&nbsp;';
		
		// the the checkbox.
		var new_check = document.createElement('input');
		new_check.setAttribute("type", "hidden");
		new_check.setAttribute("name", "invited_mails[]");
		new_check.setAttribute("value", new_mail);
		//new_check.setAttribute("style", "display: none");
		//new_check.setAttribute("checked", "checked");
		
		if(type == "invite_all")
		{
		// the delete button delete
			var new_delete = document.createElement('img');
			new_delete.setAttribute("src", "/images/btn-x.png");
			new_delete.setAttribute("class", '"pngFix"');
			new_delete.setAttribute("name", "delete");
			if (new_delete.attachEvent) {
				new_delete.attachEvent ("onclick", function(){ open_delete_buddy_mail_popup(new_mail, new_mail)});
			} else {
				new_delete.setAttribute("onclick", "open_delete_buddy_mail_popup('" + new_mail + "', '" + new_mail + "')");
			}

			var new_td1 = document.createElement('td');
			var new_td2 = document.createElement('td');
			new_td1.setAttribute("align", "center");
			new_td1.setAttribute("width","20px");
			new_td2.setAttribute("align", "left");
			
			new_td1.appendChild(new_delete);
			new_td2.appendChild(new_check);
			new_td2.appendChild(new_label);
			
			var new_tr = document.createElement('tr');
			new_tr.setAttribute("class", "buddy_mail");
			new_tr.setAttribute("id", new_mail);
			new_tr.appendChild(new_td1);
			new_tr.appendChild(new_td2);

			tbody.appendChild(new_tr);

			reorder_table_background("email_tbody", "#e6e6e6", "#ffffff");
	
		}
		else
		{
			var new_delete = document.createElement('img');
			new_delete.setAttribute("src", "/images/delete-x.png");
			new_delete.setAttribute("alt", 'X');
			new_delete.setAttribute("class", '"pngFix"');
			new_delete.style.cursor = 'pointer';
			if (new_delete.attachEvent) {
				new_delete.attachEvent ("onclick", function(){ delete_invite_friends('email_tbody', new_mail)});
			} else {
				new_delete.setAttribute("onclick", "delete_invite_friends('email_tbody', '" + new_mail + "')");
			}
			
			var new_td1 = document.createElement('td');
			new_td1.style.width = "10px";

			var new_td2 = document.createElement('td');
			new_td2.setAttribute("align","left");
			new_td2.appendChild(new_label);

			var new_td3 = document.createElement('td');
			new_td3.setAttribute("align","right");
			new_td3.appendChild(new_check);
			new_td3.appendChild(new_delete);

			var new_tr = document.createElement('tr');
			new_tr.setAttribute("id", new_mail);
			new_tr.appendChild(new_td1);
			new_tr.appendChild(new_td2);
			new_tr.appendChild(new_td3);

			tbody.appendChild(new_tr);
	
			reclass_table_odd_even("email_tbody");
		}
				
		change_send_invitation_button_status('btn_send', 'email_tbody');
		
		// after add the new mail, delete the one in the input box.
		$('new_email').value = "";		
	}
}

/**
 * Re classes the table tr's when table is messed up
 * @param String tbody_id
 */
function reclass_table_odd_even(tbody_id)
{
	tbody = $(tbody_id);
	
	attribute = 'odd';
	
	for(i=0; i<tbody.childNodes.length; i++)
	{
		var mail_tr = tbody.childNodes[i];
		if(mail_tr.nodeName.toLowerCase() == "tr")
		{	
			mail_tr.className = attribute;
			if(attribute == 'odd')
			{
				attribute = 'even';
			}
			else
			{
				attribute = 'odd';
			}
		}
	}
}

/*
	define the sorting order here.
*/
var order_m = "ASC";
var order_p = "ASC";
var order_h = "ASC";

/*
	define the sort default value.
*/
/*var sort_by_m = "smliiga_team ASC,name";
var sort_by_p = "smliiga_team ASC,name";
var sort_by_h = "smliiga_team ASC,name";*/
var sort_by_m = "";
var sort_by_p = "";
var sort_by_h = "";

function player_sort_m(url, type, new_sort_by_m)
{
	update_search_player_result(url, type, new_sort_by_m, "no_change", "no_change");
}

function player_sort_p(url, type, new_sort_by_p)
{
	update_search_player_result(url, type, "no_change", new_sort_by_p, "no_change");
}

function player_sort_h(url, type, new_sort_by_h)
{
	update_search_player_result(url, type, "no_change", "no_change", new_sort_by_h);
}

function update_sort_arrow(player, new_sort, sort_order)
{	
	var elements = $$('span.sort_icon_' + player);

	for (var i = 0, len = elements.length; i < len; ++i) {
		var item = elements[i];
		if(item.id != 'sort_icon_' + player + '_' + new_sort)
		{
			item.update('');
			item.setStyle({display: 'none'});
		}
		else
		{
			if(sort_order == 'DESC') 
			{
				item.update('<img src="/images/sort-down-arrow.png" alt="" />');
			}
			else 
			{
				item.update('<img src="/images/sort-up-arrow.png" alt="" />');
			}		
			item.setStyle({display: 'inline'});
		}
	}
}

function update_searchlist_by_position(pos)
{
	type = $('current_type').value;
	if (element = $("player_position_" + type)) {
		if (pos == 'h') 
			element.selectedIndex = 0;
		if (pos == 'p') 
			element.selectedIndex = 1;
		if (pos == 'm') 
			element.selectedIndex = 2;
		
		// Fire onchange event
		if ("fireEvent" in element) 
			element.fireEvent("onchange");
		else {
			var evt = document.createEvent("HTMLEvents");
			evt.initEvent("change", false, true);
			element.dispatchEvent(evt);
		}
	}
	
	return (type=='advanced');
}

// when the user has change the criteria of the search player select box, this function is called to update the search result.
function update_search_player_result(url, type, new_sort_by_m, new_sort_by_p, new_sort_by_h)
{
	// get the  value of the select boxes player position, player team, and player value.
	if (type == 'simple') {
		suffix = '_simple';
	}
	else if (type == 'advanced') {
		suffix = '_advanced';
	}
	else {
		suffix = '';
	}
	
	var div_id = 'div_player_search_result' + suffix;
	var position = $("player_position"+suffix).value;
	var team = $("player_team"+suffix).value;
	var value = $("player_value"+suffix).value;

	var player_sort;
	var player_type;
	var player_order;
	if(new_sort_by_m != "no_change") { player_type = 'm'; player_sort = new_sort_by_m; }
	else if(new_sort_by_p != "no_change") { player_type = 'p'; player_sort = new_sort_by_p; }
	else if(new_sort_by_h != "no_change") { player_type = 'h'; player_sort = new_sort_by_h; }
	
	if(new_sort_by_m == "no_change")
	{
		new_sort_by_m = sort_by_m;
	}
	else if(new_sort_by_m == null)
	{
		new_sort_by_m = sort_by_m;
		order_m = "DESC";
	}
	else
	{
		new_sort_by_m = get_sort_by(new_sort_by_m);
		order_m = get_order(order_m, new_sort_by_m, sort_by_m);
	}
	
	if(new_sort_by_p == "no_change")
	{
		new_sort_by_p = sort_by_p;
	}
	else if(new_sort_by_p == null)
	{
		// when the page load for the first time
		new_sort_by_p = sort_by_p;
		order_p = "DESC";	
	}
	else
	{
		new_sort_by_p = get_sort_by(new_sort_by_p);
		order_p = get_order(order_p, new_sort_by_p, sort_by_p);	
	}
	
	if(new_sort_by_h == "no_change")
	{
		new_sort_by_h = sort_by_h;
	}
	else if(new_sort_by_h == null)
	{
		new_sort_by_h = sort_by_h;
		order_h = "DESC";	
	}
	else
	{
		new_sort_by_h = get_sort_by(new_sort_by_h);
		order_h = get_order(order_h, new_sort_by_h, sort_by_h);	
	}
	
	
	sort_by_m = new_sort_by_m;
	sort_by_p = new_sort_by_p;
	sort_by_h = new_sort_by_h;
	
	if(player_type == 'm') player_order = order_m;
	else if(player_type == 'p') player_order = order_p;
	else if(player_type == 'h') player_order = order_h;
	
	paras = "player_position=" + position + "&player_team=" + team + "&player_value=" + value + "&type=" + type + "&sort_by_m="+ sort_by_m + "&sort_by_p=" + sort_by_p + "&sort_by_h=" + sort_by_h + "&order_m=" + order_m + "&order_p=" + order_p + "&order_h=" + order_h;

	// use ajax to load the page of search result to the div.
	var url2 = url+'?js=1&rand='+Math.random();

	var myAjax = new Ajax.Updater(
		div_id, 
		url2, 
		{
			method: 'get', 
			parameters: paras,
			onCreate: function() {
				$('ajax-loader-stats'+suffix).style.display = "";
			  },
			onComplete:function() {
				$('ajax-loader-stats'+suffix).style.display = "none";
				change_osta_button_status_type(type);
				update_sort_arrow(player_type, player_sort, player_order);
			}

		});	
}

/**
	help function for update_search_player_result(): check if there is any sort by attribute if not returns "none"
*/
function get_sort_by(sort_by)
{
	if(sort_by == null)
	{
		sort_by = "smliiga_team ASC,name";
	}
	else if(sort_by.length == 0)
	{
		sort_by = "smliiga_team ASC,name";
	}
	
	return sort_by;
}

/**
	Help function for update_search_player_result(): check and return sorting order.
*/
function get_order(order, new_sort_by, sort_by)
{
	// if the new_sort_by == sort by, change the sorting order, other wise, put the sorting order ASC.
	if(new_sort_by == sort_by)
	{
		if(order == "DESC")
		{
			order = "ASC";
		}
		else
		{
			order = "DESC";
		}
	}
	else
	{
		order = "DESC";
	}
	return order;
}

/*
	Sort player in the player list (search_player, choose_player, and trade_player).
*/
function sort_search_player_result(url, div_id, sort_by)
{
	var url2 = url+'?js=1&rand='+Math.random();
	var myAjax = new Ajax.Updater(
		div_id, 
		url2, 
		{
			method: 'get', 
			parameters: paras,
			onComplete:function()	{
				change_osta_button_status_type(type);
			}
		});
	
}

var	player_positions = new Array("m", "p1", "p2", "h1", "h2", "h3");

// this function deals with the choose player.
function choose_player(player_id, player_name, position, player_value, team, injury, type, imageurl, stats, translations, replace_pos)
{	
	var a="&#228;";
	var o="&#246;";
	// check if the player position is full
	var player = "";
	var notification_text;
	var notification_subject;
	
	if (replace_pos != true) {
		switch (position) {
			case "m":
				if ($("m_chosen").value == "1") {
					notification_subject = translations['error_subject'];
					notification_text = translations['error_goalie'];
					openPopup("notification_red", notification_subject, notification_text);
					return;
				}
				else {
					player = "m";
				}
				break;
				
			case "p":
				if ($("p1_chosen").value == "0") {
					player = "p1";
				}
				else 
					if ($("p2_chosen").value == "0") {
						player = "p2";
					}
					else {
						notification_subject = translations['error_subject'];
						notification_text = translations['error_defender'];
						openPopup("notification_red", notification_subject, notification_text);
						return;
					}
				break;
				
			case "h":
				if ($("h1_chosen").value == "0") {
					player = "h1";
				}
				else 
					if ($("h2_chosen").value == "0") {
						player = "h2";
					}
					else 
						if ($("h3_chosen").value == "0") {
							player = "h3";
						}
						else {
							notification_subject = translations['error_subject'];
							notification_text = translations['error_forward'];
							openPopup("notification_red", notification_subject, notification_text);
							return;
						}
				break;
				
		}
	}
	else
	{
		// Replace player, called from random player pick
		player = replace_pos;
		if ($(player + "_chosen").value == "1") return;
	}

	// check the player already chosen or not.
	if(!check_choose_players(player_id, player_name))
	{
		return;
	}

	// if player not chosen yet, and the position is not full either, add this player name to the input text box, and the player id to the hidden input, 
	if(player.length > 0)
	{		
		// Update jersey view
		$(player + "_player_id").value = player_id;
		jersey_name = $("jersey_name_"+player);
		stat_name = $("stat_name_"+player);
		jersey_name.innerHTML = player_name;
		stat_name.innerHTML = player_name;
		$("jersey_price_"+player).innerHTML = player_value + "&euro;";
		$("stat_price_"+player).innerHTML = player_value + "&euro;";
		
		if(injury == "1")
		{
			jersey_name.style.color = "#ff0000";
			stat_name.style.color = "#ff0000";
		}
		else if(injury == "2")
		{
			jersey_name.style.color = "#0000ff";
			stat_name.style.color = "#0000ff";
		}
		else if(injury == "3")
		{
			jersey_name.style.color = "#ff8c00";
			stat_name.style.color = "#ff8c00";
		}
		else 
		{
			jersey_name.style.color = "#3399cc";
			stat_name.style.color = "#3399cc";
		}
		// Update player card event
		if (jersey_name.attachEvent) {
			jersey_name.attachEvent ("onclick", function(){ load_player('/player', 'player_card', player_id); return false; });
			stat_name.attachEvent ("onclick", function(){ load_player('/player', 'player_card', player_id); return false; });
		} else {
			jersey_name.setAttribute("onclick", "load_player('/player', 'player_card', '"+player_id+"'); return false;");
			stat_name.setAttribute("onclick", "load_player('/player', 'player_card', '"+player_id+"'); return false;");
		}
		
		$(player + "_chosen").value = "1";
		if (replace_pos == "undefined") $(player + "_randomized").value = "0";
		$("jersey_button_" + player).innerHTML = translations['sell'];
		$("jersey_button_" + player).style.backgroundImage = "url(" + imageurl + "/small_green_btn.png)";
		$("jersey_button2_" + player).style.backgroundImage = "url(" + imageurl + "/small_green_btn.png)";
		$("jersey_logo_" + player).style.background = "url(" + imageurl + "/defaults/smliiga_logos_small/" + team.toLowerCase() +".png) center center no-repeat";
		$("jersey_choose_" + player).style.display = "none";
		$("jersey_data_" + player).style.display = "";
		$("stat_choose_" + player).style.display = "none";
		$("stat_data_" + player).style.display = "";
		$("stat_logo_" + player).style.background = "url(" + imageurl + "/defaults/smliiga_logos_small/" + team.toLowerCase() +".png) no-repeat";
		
		// If trades check trades left
		check_trade_players();

		// change the player stats in the data view.
		for (key in stats)
		{
			if(stats[key]=='')
			{
				$(player + "_" + key).innerHTML = "0";
			}
			else
			{
				$(player + "_" + key).innerHTML = stats[key];
			}
		}
	}
		
	// after the player name and id are inserted into the input boxes, check if all the players are inserted, enable the "continue" button.
	calculate_saldo();
	change_continue_button_status();
}

function parseSaldo(id)
{
	var saldo = $(id).innerHTML;
	saldo = saldo.replace(/[^0-9]/g, "");
	saldo = parseInt(saldo);
	return saldo;
}

/**
 * Sell or undo sell player in player selection (team creation/trades)
 * @param string position Player position
 * @param string type View type
 * @param array translations Translations array
 */
function change_player_selection_status(position, type, translations)
{
	if ($(position + "_chosen").value == "1")
	{
		// if the user want to unselect player.
		$(position + "_chosen").value = "0";
        $("jersey_button_" + position).innerHTML = translations['cancel'];
        $("jersey_button2_" + position).className = 'small_blue_button';
		$("stat_choose_" + position).style.display = "";
		$("stat_data_" + position).style.display = "none";
	}
	else if ($(position + "_chosen").value == "0")
	{
		// if the user want to select the player (again)
		
		// check if the player's saldo will exced the current saldo.
		var saldo = parseSaldo('saldo');
		var value = parseSaldo("jersey_price_" + position);
		var notification_text;
		
		if(saldo < value)
		{
			// Check if there's enough saldo
			notification_text = translations['error_balance'];
			openPopup("notification_red", null, notification_text);
			return;
		}
		
		// check the player already chosen or not.
		if(!check_choose_players($(position + "_player_id").value, $("jersey_name_"+position).innerHTML))
		{
			return;
		}
		
		$(position + "_chosen").value = "1";
		$(position + "_randomized").value = "0";
		$("stat_choose_" + position).style.display = "none";
		$("stat_data_" + position).style.display = "";

		$("jersey_button_" + position).innerHTML = translations['sell'];
        $("jersey_button2_" + position).className = 'small_green_button';
		check_trade_players();
	}
	calculate_saldo();
	change_continue_button_status();
}

function check_trade_players()
{
	if (!$("available_trade")) return;
	
	// get the trade number the user should have.
	var available_trade = $("available_trade").value;
	
	// create arrays to store the orginal players and current players.
	var original_players = new Array();
	var current_players = new Array();
	
	original_players[0] = $("old_h1_player_id").value;
	original_players[1] = $("old_h2_player_id").value;
	original_players[2] = $("old_h3_player_id").value;
	original_players[3] = $("old_p1_player_id").value;
	original_players[4] = $("old_p2_player_id").value;
	original_players[5] = $("old_m_player_id").value;
	
	current_players[0] = $("h1_player_id").value;
	current_players[1] = $("h2_player_id").value;
	current_players[2] = $("h3_player_id").value;
	current_players[3] = $("p1_player_id").value;
	current_players[4] = $("p2_player_id").value;
	current_players[5] = $("m_player_id").value;

	// compare the $original_players and $current_players to see how many difference there are.
	var num = 0; // number of same players
	
	// compare the 3 forwards
	for(i=0; i<3; i++)
	{
		for(j=0; j<3; j++)
		{
			if(current_players[i] == original_players[j])
			{
				num = num + 1;				
			}
		}
	}

	// compare the 2 defensemen.
	for(i=3; i<5; i++)
	{
		for(j=3; j<5; j++)
		{
			if(current_players[i] == original_players[j])
			{
				num = num + 1;
			}
		}
	}
	
	// compare the last goalie.
	if(current_players[5] == original_players[5])
	{
		num = num + 1;
	}
	
	trade_needed = 6 - num;
	// calculate the trade left.
	
	$("trade").innerHTML = available_trade - trade_needed;

}


// everytime the player is selected or deleted, this function will be called to enable and disable the "Continue" button, which inserts the players team relationships.
function change_continue_button_status()
{
	// when the 6 players are not chosen yet, disable the continue button.
	for(i=0; i<(player_positions.length); i++)
	{
		if($(player_positions[i] + "_chosen").value == "0")
		{
			$("create_button").style.display = "none";
			$("create_button_disabled").style.display = "";
			return;
		}
	}
	var saldo = parseSaldo('saldo');
	
	// check the saldo number, if it is minus, disable the button too.
	if (saldo < 0)
	{
		$("create_button").style.display = "none";
		$("create_button_disabled").style.display = "";
		return;
	}
	
	// check the trade left, if the trade left is more minus, then disabled the button.
	if($('trade'))
	{
		// check if there is enough trade
		if(parseInt(($("trade").innerHTML)) < 0)
		{
			$("create_button").style.display = "none";
			$("create_button_disabled").style.display = "";
			return;
		}
	}

	$("create_button").style.display = "";
	$("create_button_disabled").style.display = "none";

	return;
}

// this function is to check if the selected palyer is already choosen by the user.
function check_choose_players(player_id, player_name)
{
	var notification_text;
	// check if this player is already selected.
		
	for(i=0; i<(player_positions.length); i++)
	{
		if(player_id == $(player_positions[i] + "_player_id").value && $(player_positions[i] + "_chosen").value == "1")
		{
			notification_text = "Pelaaja " + player_name + " on jo valittu!";
			openPopup("notification", null, notification_text);
			return false;
		}
	}
	return true;
}

// this function is used to calculate the value of saldo after the user select or remove the player.
function calculate_saldo()
{
	var starting_saldo = parseInt($('starting_saldo').value);
	for(i=0; i<player_positions.length; i++)
	{
		if($(player_positions[i] + "_chosen").value == "1")
		{
			var player_value = parseSaldo("jersey_price_" + player_positions[i]);
			starting_saldo = starting_saldo - player_value;
		}
	}
	
	$("saldo").innerHTML = formatThousand(starting_saldo)+"&euro;";	
	change_osta_button_status();
}


/*
	this function take the value of the saldo and compare to the each players' value, if they value is greater than the saldo, hide the button, otherwise, display the osta button;
	and if the player is already in slot, disable the saldo as well.
*/
function change_osta_button_status()
{
	// check the total saldo, if it is smaller than any player's value, then hiden the osta,
	var saldo = parseSaldo('saldo');
	//osta_btns = document.getElementsByClassName("player_result_id");
	var i=0;
	var k=0;
	var osta_btns;
	var tab_osta_btns;
	var id;
	var value;
	osta_btns = new Array();
	tag_osta_btns = new Array();
	
	// get the searched player ids inputs and tagged player ids inputs.
	inputs = document.getElementsByTagName("input");
	for(j=0;j<inputs.length;j++)
	{
		if(inputs[j].className == "player_result_id")
		{
			osta_btns[i] = inputs[j];
			i++;
			
		}
		else if(inputs[j].className == "tag_player_result_id")
		{
			tag_osta_btns[k] = inputs[j];
			k++;
			
		}
	}
	
	// check the each player in the player list, if their value is bigger than saldo, or if they are already in the selection slots.
	for(i=0;i<osta_btns.length;i++)
	{		
		// check the value VS. saldo
		id = osta_btns[i].value;	
		value = parseSaldo(id + "_player_value");

		if(value > saldo)
		{
			 $(id + "_osta_btn").style.display = "none";
		}
		else
		{
			$(id + "_osta_btn").style.display = "";
		}
		// check if the player is already in the player slot.		
		change_osta_by_player_existence("m", id, "");
		change_osta_by_player_existence("p1", id, "");
		change_osta_by_player_existence("p2", id, "");
		change_osta_by_player_existence("h1", id, "");
		change_osta_by_player_existence("h2", id, "");
		change_osta_by_player_existence("h3", id, "");
	}
	
	for(i=0;i<tag_osta_btns.length;i++)
	{
		id = tag_osta_btns[i].value;	
		value = parseSaldo("tag_" + id + "_player_value");
		if(value > saldo)
		{
			 $("tag_" + id + "_osta_btn").style.display = "none";
		}
		else
		{
			$("tag_" + id + "_osta_btn").style.display = "";
		}
		change_osta_by_player_existence("m", id, "tag_");
		change_osta_by_player_existence("p1", id, "tag_");
		change_osta_by_player_existence("p2", id, "tag_");
		change_osta_by_player_existence("h1", id, "tag_");
		change_osta_by_player_existence("h2", id, "tag_");
		change_osta_by_player_existence("h3", id, "tag_");
	}
	return;
}

/*
	This function will check if the current_player(which is in the player slot) has the same id as in the search_player_id (which is in the player list). 
	If they are the same, hide the osta button of the one in the player list.
*/
function change_osta_by_player_existence(current_player, search_player_id, prefix)
{
	if($(current_player + "_player_id").value == search_player_id && $(current_player + "_chosen").value == "1")
	{
		// Change player row class to change color to blue
		var trElement = $(prefix + search_player_id + "_tr");
        if (trElement.className == "odd")
        {
            trElement.className = "odd_selected";
        }
        if (trElement.className == "even")
        {
            trElement.className = "even_selected";
        }		
        // Hide osta button
        $(prefix + search_player_id + "_osta_btn").style.display = "none";
	}
	return;
}

/*
	this function will check the type, if it is choose player and trade players, we call change_osta_button_status() function.
*/
function change_osta_button_status_type(type)
{
	if(type == "advanced" || type == "simple")
	{
		change_osta_button_status();
	}
}

function formatThousand(stringVal)
{
	stringVal=stringVal+'';
	var left_chars=stringVal.length%3;
	var string_result = stringVal.substring(0, left_chars);
	if(stringVal.length>left_chars)
	{
		for(i=left_chars; i<stringVal.length;i=i+3)
		{
			string_result=string_result+' '+stringVal.substr(i,3);
		}
	}
	return string_result;
}

function clearWhiteSpace(stringVal)
{
	var string_result="";
	for(i=0; i<stringVal.length; i++)
	{
		if(stringVal.charAt(i)==" ")
		{
			string_result=string_result+"";	
		}
		else
		{
			string_result=string_result+stringVal.charAt(i);
		}
		
	}
	return string_result;
}

/*
 * Load player card for player with specific player_id
 */
function load_player(url, player_div, player_id, phase)
{
	if (!phase) phase = 0;
	var url2 = url+'?js=1&rand='+Math.random();
	var myAjax = new Ajax.Updater(
		player_div, 
		url2, 
		{
			method: 'get', 
			parameters: "player_id=" + player_id + "&phase=" + phase,
			evalScripts: true,
			onSuccess: function() {
				if ($('div_search_players'))
				{
					hideById('div_search_players');
					showById('whitearea');
				}
				showById(player_div);
				fadeInBackground();
			}
		});
}

/*
 * Player tagging functions
 */
function tag_player(player_id, btn_type, notification_header, notification_header_full, notification_text_full, url, url_tagged)
{			
	var is_full = 0;
	var notification_head = notification_header;
	var notification_text = '';	
	
	// Check if user have 5 tagged players
	//if (btn_type == "tag" && $('taggedCount').value >= 5)
	//{
	//	is_full = 1;
	//	notification_head = notification_header_full;
	//	notification_text = notification_text_full;
	//}
	
	//else if (btn_type == "tag" && $('taggedCount').value < 5)
	if (btn_type == "tag")
	{
		$('taggedCount').value = parseInt($('taggedCount').value) + 1;
	}
	
	else if (btn_type == "untag" && $('taggedCount').value > 0)
	{
		$('taggedCount').value = parseInt($('taggedCount').value) - 1;
	}	
	
	// use ajax to load a page checking if this user is already tagged,  or if there are five players tagged already, or tag the player if everthing goes right.
	var params = "player_id=" + player_id + "&button=" + btn_type;	
	var url2 = url+'?js=1&rand='+Math.random();
	if(url_tagged == null)
	{
		var myAjax = new Ajax.Request(				 
			url2, 
			{				
				method: 'get', 
				parameters: params,
				onComplete:function()	{
					change_tag_btn_status(player_id, btn_type, is_full);	
					openPopup('notification', notification_head, notification_text);
				}
			});
	}
	else
	{
		var myAjax = new Ajax.Request(				 
			url2, 
			{
				method: 'get', 
				parameters: params,
				onComplete:function()	{							
					change_tag_btn_status(player_id, btn_type, is_full);	
					openPopup('notification', notification_head, notification_text);
					change_view('trades', 'tagged_players', url_tagged, null, 1);
				}
			});
	}
}

function tag_in_player_card(player_id, notification_header, notification_header_full, notification_text_full, notification_header_already, url, button, alreadyTagged)
{
	var btn_type=button.alt;		
	var notification_head = notification_header;
	var notification_text = '';
	
	// Check if player already tagged by user
	if (alreadyTagged == 1)
	{
		notification_head = notification_header_already;
	}
	
	// Check if user have 5 tagged players
	//else if ($('taggedCardCount').value >= 5)
	//{
	//	notification_head = notification_header_full;
	//	notification_text = notification_text_full;
	//}
		
	// use ajax to load a page checking if this user is already tagged,  or if there are five players tagged already, or tag the player if everthing goes right.
	var params = "player_id=" + player_id + "&button=" + btn_type;
	var url2 = url+'?js=1&rand='+Math.random();
	var myAjax = new Ajax.Request(				 
		url2, 
		{
			method: 'get', 
			parameters: params,
			onComplete:function()	{					
				openPopup('notification', notification_head, notification_text);				
			}
		});		 
}

function change_tag_btn_status(player_id, btn_type, is_full)
{			
	if (is_full == 1 && btn_type == "tag")
	{
		if ($("t" + player_id + "_tag_btn").style.display == "none")
		{
			$("t" + player_id + "_tag_btn").style.display = "none";
			$("u" + player_id + "_untag_btn").style.display = "block";			
		}

		else 
		{
			$("t" + player_id + "_tag_btn").style.display="block";
			$("u" + player_id + "_untag_btn").style.display="none";		
		}			
	}
	
	else if (btn_type == "tag")
	{	
		$("t" + player_id + "_tag_btn").style.display = "none";
		$("u" + player_id + "_untag_btn").style.display = "block";
	}
	
	else 
	{
		$("t" + player_id + "_tag_btn").style.display="block";
		$("u" + player_id + "_untag_btn").style.display="none";		
	}	
}


function tag_untag_player(player_id, player_name, div_id, container_id, url, button)
{
	btn_type=button.alt;
	// use ajax to load a page checking if this user is already tagged,  or if there are five players tagged already, or tag the player if everthing goes right.
	var params = "player_id=" + player_id + "&button=" + btn_type;
	var url2 = url+'?js=1&rand='+Math.random();
	var myAjax = new Ajax.Updater(
		div_id, 
		url2, 
		{
			method: 'get', 
			parameters: params,
			onComplete:function()	{
				openPopup(container_id, true);	
				change_tag_btn_status(player_id,div_id);				
			}
		});		
}
function refresh_tag_list(player_id, div_id, url)
{
	var params = "player_id="+player_id;
	var url2 = url+'?js=1&rand='+Math.random();
	var myAjax = new Ajax.Updater(
			div_id, 
			url2, 
			{
				method: 'get',
				parameters: params,
				onComplete:function()	{
					change_osta_button_status();
				}
			}
		);
}

function delete_tag_player(view, div_id, refresh_url, delete_url, player_id, type)
{	
    if ($('taggedCount').value > 0)
    {
    	$('taggedCount').value = parseInt($('taggedCount').value) - 1;
    }

	var params = "player_id="+player_id+"&button=untag";
	var url2 = delete_url+'?js=1&rand='+Math.random();

	new Ajax.Request( 
		url2, 
		{
			method: 'get', 
			parameters: params,
			onSuccess:function() {
				if(type != 'undefined')
				{
					change_playersearch_view('tagged', '_' + type);
				}
				else
				{
					change_view(view, div_id, refresh_url, null, 1);
					change_tag_btn_status(player_id, 'untag');
				}
			}
		});

		
}

function change_view(view, div_id, url, do_check, ajax)
{
	if (ajax == null)
	{
		ajaxparam = 1;
	}
	
	else 
	{
		ajaxparam = null;
	}
	
	var params = "view=" + view + "&ajax="+ajaxparam;
	var url2 = url+'?js=1&rand='+Math.random();	
	if (do_check == null)
	{
		new Ajax.Updater(
				div_id, 
				url2, 
				{
					method: 'get', 
					parameters: params
				});
	}
	else
	{
		new Ajax.Updater(
				div_id, 
				url2, 
				{
					method: 'get', 
					parameters: params,
					onComplete:function() {						 
						check_trade_players();
						change_osta_button_status();
					}
				});
	}
}

function load_smliiga_team_stats(teamId, teamName, position, phase, round, order, asc, img_url, loading_image)
{
	var params="teamId="+teamId+"&teamName="+teamName+"&position="+position+"&phase="+phase+"&round="+round+"&order="+order+"&asc="+asc;
	var url2 = '/sm-liiga/ajax-stats-team-season?rand='+Math.random();
	var div_id = 'stats_'+position+'_'+teamId;
	var loadTransfersAjax = new Ajax.Updater(
		div_id, 
		url2, 
		{
			method: "get", 
			parameters: params,
			onCreate: function() {
				if (loading_image == 1) $(div_id).innerHTML = '<img src="'+img_url+'/ajax-loader_green.gif" alt="" style="padding-left:270px;" />';
			  }
		});	
}

function hideShowSMliigaGameReports(url, match_id, hometeam, awayteam, background, img_url)
{	
	if ($('match_statistics_'+match_id).style.display == 'block')
	{
        $('match_statistics_tablerow_'+match_id).style.display = 'none';               
		$('match_statistics_'+match_id).style.display = 'none';        		  
		$('match_'+match_id).style.background = '#'+background;		
		$('match_'+match_id).style.marginTop = '0';
		$('match_'+match_id).style.color = '#000000';
		$('match_lineup_link_'+match_id).style.color = '#3399cc';
		$('match_report_link_'+match_id).style.color = '#3399cc';
				
		if (background == 'ebf8fd')
		{
			$('match_'+match_id).style.borderTop = '1px solid #cccccc';	
			$('match_'+match_id).style.borderBottom = '1px solid #cccccc';
			$('match_'+match_id).style.borderLeft = 'none';	
			$('match_'+match_id).style.borderRight = 'none';		
		}
		
		else 
		{
			$('match_'+match_id).style.border = 'none';
		}
	} 
	else
	{	
		var params="matchId="+match_id+"&homeTeam="+hometeam+"&awayTeam="+awayteam;
		var url2 = url+'?rand='+Math.random();
		var target = 'match_statistics_'+match_id;
		var myAjax = new Ajax.Updater(
			target, 
			url2, 
			{
				method: 'get', 
				parameters: params,
				onCreate: function() {
                    $('match_statistics_tablerow_'+match_id).style.display = '';                                       
					$('match_statistics_'+match_id).style.display = 'block';                    					
					$('match_lineups_'+match_id).style.display = 'none';
					$('match_'+match_id).style.background = 'url('+img_url+'/title-bar-bg.png)';
					$('match_'+match_id).style.color = '#ffffff';
					$('match_'+match_id).style.border = '1px solid #a4a3a4';
					$('match_'+match_id).style.marginTop = '2px';
					$('match_statistics_'+match_id).innerHTML = '<img src="'+img_url+'/ajax-loader_black.gif" alt="" style="padding-left:270px;" />';
		    		$('match_lineup_link_'+match_id).style.color = '#ffffff';
					$('match_report_link_'+match_id).style.color = '#ffffff';
				}
			});		
	}
}

function hideShowFrontpageGameReports(url, match_id, hometeam, awayteam, background, img_url)
{	
	if ($('match_statistics_'+match_id).style.display == 'block')
	{
		$('match_statistics_'+match_id).style.display = 'none';
	}
	else
	{
		var params="matchId="+match_id+"&homeTeam="+hometeam+"&awayTeam="+awayteam;
		var url2 = url+'?rand='+Math.random();
		var target = 'match_statistics_'+match_id;
		var myAjax = new Ajax.Updater(
			target,
			url2,
			{
				method: 'get',
				parameters: params,
				onCreate: function() {
					$('match_statistics_'+match_id).style.display = 'block';					
					$('match_lineups_'+match_id).style.display = 'none';
				}
			});		
	}
}

function hideShowSMliigaLineups(url, match_id, background, img_url)
{
	if ($('match_lineups_'+match_id).style.display == 'block')
	{
        $('match_lineups_tablerow_'+match_id).style.display = 'none';
		$('match_lineups_'+match_id).style.display = 'none';		  
		$('match_'+match_id).style.background = '#'+background;			
		$('match_lineups_'+match_id).style.marginTop = '0';
		$('match_'+match_id).style.color = '#000000';
		$('match_lineup_link_'+match_id).style.color = '#3399cc';
		$('match_report_link_'+match_id).style.color = '#3399cc';

		if (background == 'ebf8fd')
		{
			$('match_'+match_id).style.borderTop = '1px solid #cccccc';	
			$('match_'+match_id).style.borderBottom = '1px solid #cccccc';
			$('match_'+match_id).style.borderLeft = 'none';	
			$('match_'+match_id).style.borderRight = 'none';		
		}
		
		else 
		{
			$('match_'+match_id).style.border = 'none';
		}
	} 
	else
	{
		var params="matchId="+match_id;
		var url2 = url+'?rand='+Math.random();
		var target = 'match_lineups_'+match_id;
		var myAjax = new Ajax.Updater(
			target, 
			url2, 
			{
				method: 'get',
				parameters: params,
				onCreate: function() {                    
					$('match_statistics_'+match_id).style.display = 'none';
                    $('match_lineups_tablerow_'+match_id).style.display = '';
					$('match_lineups_'+match_id).style.display = 'block';
					$('match_'+match_id).style.background = 'url('+img_url+'/title-bar-bg.png)';
					$('match_'+match_id).style.color = '#ffffff';
					$('match_'+match_id).style.border = '1px solid #a4a3a4';
					$('match_'+match_id).style.marginTop = '2px';
					$('match_lineups_'+match_id).innerHTML = '<img src="'+img_url+'/ajax-loader_black.gif" alt="" style="padding-left:270px;" />';
		    		$('match_lineup_link_'+match_id).style.color = '#ffffff';
					$('match_report_link_'+match_id).style.color = '#ffffff';
				}
			});
	}
}

function hideShowFrontpageLineups(url, match_id, background, img_url)
{
	if ($('match_lineups_'+match_id).style.display == 'block')
	{
		$('match_lineups_'+match_id).style.display = 'none';		  
	} 
	else
	{
		var params="matchId="+match_id;
		var url2 = url+'?rand='+Math.random();
		var target = 'match_lineups_'+match_id;
		var myAjax = new Ajax.Updater(
			target, 
			url2, 
			{
				method: 'get',
				parameters: params,
				onCreate: function() {
					$('match_statistics_'+match_id).style.display = 'none';
					$('match_lineups_'+match_id).style.display = 'block';
				}
			});
	}
}

function update_results_statistics(url, div_id, phase, round, type, img_url)
{
	var params="phase="+phase+"&round="+round+"&type="+type;
	var url2 = url+'?js=1&rand='+Math.random();
	var myAjax = new Ajax.Updater(
		div_id, 
		url2, 
		{
			method: 'get',
			parameters: params,
			onCreate: function () {
				$('ajax-loader-stats').style.display = '';
			},
			onComplete: function() {
				$('ajax-loader-stats').style.display = 'none';
				$('active_type').value = type;
			}
		});
}
function update_team_round_statistics(url, div_id, team, phase, round)
{
	var params="phase="+phase+"&round="+round+"&team="+team;
	var url2 = url+'?js=1&rand='+Math.random();
	var myAjax = new Ajax.Updater(
		div_id, 
		url2, 
		{
			method: 'get',
			parameters: params,
			onComplete: function() {
				$(div_id).style.display = 'block';
			}
		});
}

function change_send_feedback_button_status(textarea_id, button_id, email_id, name_id)
{	var status=false;
	var content_length=trimText($F(textarea_id)).length;
	var cont=true;
	if(content_length>0)
	{
		status=true;	
	}
	else if(content_length==0)
	{
		status=false;
	}
		
	if(status)
	{
		$(button_id).className = "button";
		$(button_id).disabled = false;
	}
	else
	{
		$(button_id).className = "button_inactive";
		$(button_id).disabled = true;
	}
}
function showLength(feedback_field_id,show_field_id, length_size)
{
	var field_length=$(feedback_field_id).innerHTML.length;
	$(show_field_id).innerHTML=length_size-field_length;
	
}
function trimText(text) {
	return text.replace(/^\s+|\s+$/g,"");
}

function switchTeam(url, id, to_payment_page)
{
	if (to_payment_page == undefined) {
		document.location = url + '/0/' + id;
	}
	else {
		document.location = url + '/0/' + id + '?payment=1';		
	}
}

function changeTopTrades(type, title)
{	
	$('top_trades_title').innerHTML = '<h3>'+title+'</h3>';
	
	if (type == 'bought')
	{
		$('sold_players').style.display = 'none';
		$('top_players').style.display = 'block';
	}
	
	else
	{
		$('sold_players').style.display = 'block';
		$('top_players').style.display = 'none';		
	}
}
function update_frontpage_matches(url, div_id, dateindex)
{
	var params="dateindex="+dateindex;
	var url2 = url+'?js=1&rand='+Math.random();
	var myAjax = new Ajax.Updater(
		div_id,
		url2,
		{
			method: 'get',
			parameters: params
		});
}
function updatePlayerCardGraph(dataUrl, flashUrl, plus, lastPage)
{
	tmp = parseInt($('graphStart').value);
	if (plus > 0) {
		if (tmp < lastPage) {
			tmp = tmp + 1;
		}
		else
		{
			tmp = lastPage;
		}
		$('graphStart').value = tmp;
	}
	if (plus < 0) {
		if (tmp > 1) {
			tmp = tmp - 1;
			$('graphStart').value = tmp;
		}
	}

	var param1 = {"data": dataUrl+"/"+tmp+"?js=1&random="+Math.random()};
	var param2 = {"wmode": "transparent","allowscriptaccess": "always"};
	swfobject.embedSWF(flashUrl, "player_graph", "283", "122", "9.0.0", null, param1, param2 );
}

function hide_show_search_by(value) {
	if ($('form-favouriteteam')) {
		if (value == 'team') $('form-favouriteteam').style.display = 'none';
		else $('form-favouriteteam').style.display = '';
	}
}

function change_group_standings_graph(value, flashUrl, baseUrl, group_id, team1, team2, team3, phase, styles) {
	if ($('group_team_standings')) {
		if (value == 'standings')
		{
			$('group_team_standings').style.display = '';
			$('group_team_graphs').style.display = 'none';
		}
		else
		{
			$('group_team_standings').style.display = 'none';
			$('group_team_graphs').style.display = '';
			if ($('group_team_graphs').innerHTML == '')
			{
				loadGroupGraphs(flashUrl, baseUrl, group_id, phase, team1, team2, team3, styles);
			}
		}
	}
}
function loadGroupGraphs(flashUrl, baseUrl, group_id, phase, team_id1, team_id2, team_id3, styles)
{
	var params="groupId="+group_id+"&phase="+phase+"&teamId1="+team_id1+"&teamId2="+team_id2+"&teamId3="+team_id3;
	var url2 = baseUrl+'/group/ajax-team-graphs?js=1&rand='+Math.random();
	var target = 'group_team_graphs';
	var myAjax = new Ajax.Updater(
		target, 
		url2, 
		{
			method: 'get',
			parameters: params,
			onComplete: function() {
				if(styles != undefined)
				{
					if(styles['button'] != undefined)
					{
						var elements = $$('.button');
						for (var i=0; i<elements.length; i++) {
							if (styles['button']['background'] != undefined) {
								elements[i].style.background = styles['button']['background'];
							}
							if (styles['button']['color'] != undefined) {
								elements[i].style.color = styles['button']['color'];
							}
							if (styles['button']['border'] != undefined) {
								elements[i].style.borderColor = styles['button']['border'];
							}
						}
					}
				}
				swfobject.embedSWF(flashUrl+"/open-flash-chart.swf", "flash_group_chart", "686", "250", "9.0.0", null, {"data":baseUrl+"/group/graph-data/"+team_id1+"/"+team_id2+"/"+team_id3+"/"+phase+"?js=1&random="+Math.random()+""}, {"wmode":"transparent","allowscriptaccess":"always"} );
			}
		});
}

function changeSponsorGroupStyles(styles, bgimage)
{
	// Form background style string
	if (styles['background'] != undefined)
	{
		if (styles['background']['color']  != undefined) $('content_panels').style.backgroundColor = styles['background']['color']; 
		if (styles['background']['posx']   != undefined	&& styles['background']['posy']!= undefined) $('content_panels').style.backgroundPosition = styles['background']['posx']+' '+styles['background']['posy']; 
		if (styles['background']['repeat'] != undefined) $('content_panels').style.backgroundRepeat = styles['background']['repeat']; 
	}
	if (bgimage != undefined)
	{
		$('content_panels').style.backgroundImage = 'url("/shared/images/group/background/'+bgimage+'")';
	}
	
	if (styles['images'] != undefined)
	{
		if (styles['images']['logowidth'] != undefined)
		{
			if ($('group_yellow_header_logo')) $('group_yellow_header_logo').style.width = (parseInt(styles['images']['logowidth']) + 19)+'px'; 
			if ($('group_yellow_header_text')) $('group_yellow_header_text').style.width = (445 - parseInt(styles['images']['logowidth']))+'px'; 
		}
	}
	
	if(styles['text'] != undefined)
	{
		if (styles['text']['color'] != undefined) {
			var elements = $$('.grodsdup_style_text');
			for (var i=0; i<elements.length; i++) {
				elements[i].style.color = styles['text']['color'];
			}
		}
		if (styles['text']['link'] != undefined) {
			var elements = $$('a.group_style');
			for (var i=0; i<elements.length; i++) {
				elements[i].style.color = styles['text']['link'];
			}
			var elements = $$('.group_style_links');
			for (var i=0; i<elements.length; i++) {
				var links = elements[i].getElementsByTagName('a');
				for (var k=0; k<links.length; k++) {
					links[k].style.color = styles['text']['link'];
				}
			}
		}
	}
	if(styles['h1'] != undefined)
	{
		var elements = $$('h1.group_style');
		for (var i=0; i<elements.length; i++) {
			if (styles['h1']['background'] != undefined) {
				elements[i].style.background = styles['h1']['background'];
				if ($('group_yellow_header_background')) $('group_yellow_header_background').style.background = styles['h1']['background'];
			}
			if (styles['h1']['color'] != undefined) {
				elements[i].style.color = styles['h1']['color'];
				if ($('group_yellow_header_text')) $('group_yellow_header_text').style.color = styles['h1']['color'];
			}
		}
	}
	if(styles['table'] != undefined)
	{
		if (styles['table']['header'] != undefined) {
			var elements = $$('th.group_style');
			for (var i=0; i<elements.length; i++) {
				elements[i].style.color = styles['table']['header'];
			}
		}
		var elements = $$('.group_style_odd');
		for (var i=0; i<elements.length; i++) {
			if (styles['table']['bg1'] != undefined) {
				elements[i].style.backgroundColor = styles['table']['bg1'];
			}
			if (styles['table']['border'] != undefined) {
				elements[i].style.borderColor = styles['table']['border'];
			}
		}
		var elements = $$('.group_style_even');
		for (var i=0; i<elements.length; i++) {
			if (styles['table']['bg2'] != undefined) {
				elements[i].style.backgroundColor = styles['table']['bg2'];
			}
			if (styles['table']['border'] != undefined) {
				elements[i].style.borderColor = styles['table']['border'];
			}
		}
		if (styles['table']['border'] != undefined) {
			if ($('profilepage_rightside')) $('profilepage_rightside').style.borderColor = styles['table']['border'];
		}
	}
	if(styles['button'] != undefined)
	{
		var elements = $$('.button');
		for (var i=0; i<elements.length; i++) {
			if (styles['button']['background'] != undefined) {
				elements[i].style.background = styles['button']['background'];
			}
			if (styles['button']['color'] != undefined) {
				elements[i].style.color = styles['button']['color'];
			}
			if (styles['button']['border'] != undefined) {
				elements[i].style.borderColor = styles['button']['border'];
			}
		}
	}
}

function showTextById(id, text)
{
	if (el = $(id))
	{
		if (el.style.display != 'none' && el.innerHTML.replace(/<(?:.|\s)*?>/g,'') == text.replace(/<(?:.|\s)*?>/g,''))
		{
			el.style.display = 'none';
		}
		else
		{
			el.innerHTML = text;
			el.style.display = '';
		}
	}
}

function groupInvite_markAllFriends(checked)
{
	var elements = $$('.friend_checkbox');
	if (checked)
	{
		for (var i=0; i<elements.length; i++)
		{
			elements[i].checked = true;
		}
	}
	else
	{
		for (var i=0; i<elements.length; i++)
		{
			elements[i].checked = false;
		}
	}
}

function groupInvite_checkAllChecked()
{
	var elements = $$('.friend_checkbox');
	var all = true;
	for (var i=0; i<elements.length; i++)
	{
		if (elements[i].checked == false) all = false;
	}
	if (all == true)
	{
		$('cb_check_all').checked = true;
	}
	else
	{
		$('cb_check_all').checked = false;
	}
}

function callUrl(url, redirect)
{
	var url2 = url+'?js=1&rand='+Math.random();
	if (redirect == undefined)
	{
		var myAjax = new Ajax.Request(				 
			url2, 
			{
				method: 'get'
			});
	}
	else
	{
		var myAjax = new Ajax.Request(				 
			url2, 
			{
				method: 'get',
				onComplete: function() {
					document.location = redirect; 
				}
			});
	}
}

function joinOpenGroup(groupName)
{
	$('group-name').value = groupName;
	$('group-password').value = '';
	$('frm_group').submit();
}

function show_hide_group_settings(type)
{
	if (type == 'show')
	{
		$('group_settings_box').style.display = '';
		$('settings_open').style.display = 'none';
		$('settings_close').style.display = '';
	}
	else
	{
		$('group_settings_box').style.display = 'none';
		$('settings_open').style.display = '';
		$('settings_close').style.display = 'none';
	}
}

function update_users_playerselection_mode(url, mode)
{
	var url2 = url+'?js=1&rand='+Math.random();
	var params = "mode="+mode;
	var myAjax = new Ajax.Request(url2, {method: 'get',	parameters: params} );
}

function change_playerselection_mode(url, mode, update)
{
	$('current_type').value = mode;
	if (mode == 'advanced')
	{
		if (update) update_users_playerselection_mode(url, 1);
		$('advanced_mode_button').className = "trade_view_select_button_left_active";
		$('simple_mode_button').className = "trade_view_select_button_right";
		//if ($('team_playerselect_seasonteam_box_simple')) $('team_playerselect_seasonteam_box_simple').style.display = 'none';
		$('team_playerselect_playerlist_box_simple').style.display = 'none';
		$('div_player_search_result_simple').innerHTML = '';
		$('team_playerselect_playerlist_box_advanced').style.display = '';
		//if ($('team_playerselect_seasonteam_box_advanced')) $('team_playerselect_seasonteam_box_advanced').style.display = '';
		$('team_playerselect_stats_box').style.display = '';
		
		// update old team selection
		$('player_position_advanced').selectedIndex = $('player_position_simple').selectedIndex;
		$('player_team_advanced').selectedIndex = $('player_team_simple').selectedIndex;
		$('player_value_advanced').selectedIndex = $('player_value_simple').selectedIndex;
		
		// load the player search result, i.e. all the players in this case.
		change_playersearch_view('search', '_advanced');
		update_search_player_result('/team/search-players', 'advanced');
	}
	if (mode == 'simple')
	{
		if (update) update_users_playerselection_mode(url, 0);
		$('advanced_mode_button').className = "trade_view_select_button_left";
		$('simple_mode_button').className = "trade_view_select_button_right_active";
		$('team_playerselect_playerlist_box_advanced').style.display = 'none';
		$('div_player_search_result_advanced').innerHTML = '';
		if ($('team_playerselect_seasonteam_box_advanced')) $('team_playerselect_seasonteam_box_advanced').style.display = 'none';
		$('team_playerselect_stats_box').style.display = 'none';
		if ($('team_playerselect_seasonteam_box_simple')) $('team_playerselect_seasonteam_box_simple').style.display = '';
		$('team_playerselect_playerlist_box_simple').style.display = '';

		// update old team selection
		$('player_position_simple').selectedIndex = $('player_position_advanced').selectedIndex;
		$('player_team_simple').selectedIndex = $('player_team_advanced').selectedIndex;
		$('player_value_simple').selectedIndex = $('player_value_advanced').selectedIndex;
		change_playersearch_view('search', '_simple');
		update_search_player_result('/team/search-players', 'simple');
	}
}

function pick_random_all(url, imageurl, type, favteam, translations)
{
	var random_count = 0;
	var mode = 0;

	if ($("h1_chosen").value == "0" || $("h1_randomized").value == "1") random_count++;
	if ($("h2_chosen").value == "0" || $("h2_randomized").value == "1") random_count++;
	if ($("h3_chosen").value == "0" || $("h3_randomized").value == "1") random_count++;
	if ($("p1_chosen").value == "0" || $("p1_randomized").value == "1") random_count++;
	if ($("p2_chosen").value == "0" || $("p2_randomized").value == "1") random_count++;
	if ($("m_chosen").value == "0" || $("m_randomized").value == "1") random_count++;
	
	if (random_count == 6 && favteam != '') {
		// All player are randomized and favteam is present, select 3 from that team
		var fav_count = 0;
		var random;
		var fav = '';

		random = Math.floor(Math.random()*2);
		fav = 'no_'+favteam;
		if (random == 1) {
			fav_count++;
			fav = 'yes_'+favteam;
		}
		pick_random_player(url, 'h', 'h1', imageurl, type, true, fav, 0, translations);
		$("h1_randomized").value = "1"
		
		random = Math.floor(Math.random()*2);
		fav = 'no_'+favteam;
		if (random == 1) {
			fav_count++;
			fav = 'yes_'+favteam;
		}
		pick_random_player(url, 'h', 'h2', imageurl, type, true, fav, 0, translations);
		$("h2_randomized").value = "1"
		
		random = Math.floor(Math.random()*2);
		fav = 'no_'+favteam;
		if (random == 1) {
			fav_count++;
			fav = 'yes_'+favteam;
		}
		pick_random_player(url, 'h', 'h3', imageurl, type, true, fav, 0, translations);
		$("h3_randomized").value = "1"
		
		random = Math.floor(Math.random()*2);
		fav = 'no_'+favteam;
		if ((random == 1 && fav_count < 3) || (fav_count == 0)) {
			fav_count++;
			fav = 'yes_'+favteam;
		}
		pick_random_player(url, 'm', 'm', imageurl, type, true, fav, 0, translations);
		$("m_randomized").value = "1"
		

		if ($("p2_chosen").value == "0") mode = 2;
		random = Math.floor(Math.random()*2);
		fav = 'no_'+favteam;
		if ((random == 1 && fav_count < 3) || (fav_count == 1)) {
			fav_count++;
			fav = 'yes_'+favteam;
		}
		pick_random_player(url, 'p', 'p1', imageurl, type, true, fav, mode, translations);
		$("p1_randomized").value = "1"
		
		random = Math.floor(Math.random()*2);
		fav = 'no_'+favteam;
		if ((random == 1 && fav_count < 3) || (fav_count == 2)) {
			fav_count++;
			fav = 'yes_'+favteam;
		}
		pick_random_player(url, 'p', 'p2', imageurl, type, true, fav, 1, translations);
		$("p2_randomized").value = "1"
		
	}
	else {
		var empty = 0;
		// Randomize all but manually selected players
		if ($("m_chosen").value == "0" || $("m_randomized").value == "1") {
			if ($("h1_chosen").value == "0") empty++;
			if ($("h2_chosen").value == "0") empty++;
			if ($("h3_chosen").value == "0") empty++;
			if ($("p1_chosen").value == "0") empty++;
			if ($("p2_chosen").value == "0") empty++;
			if (empty == 1) mode = 2;
			if (random_count == 1) mode = 1;
			pick_random_player(url, 'm', 'm', imageurl, type, true, '', mode, translations);
			$("m_randomized").value = "1";
			random_count--;
		}
		if ($("h1_chosen").value == "0" || $("h1_randomized").value == "1") {
			if ($("h2_chosen").value == "0") empty++;
			if ($("h3_chosen").value == "0") empty++;
			if ($("p1_chosen").value == "0") empty++;
			if ($("p2_chosen").value == "0") empty++;
			if (empty == 1) mode = 2;
			if (random_count == 1) mode = 1;
			pick_random_player(url, 'h', 'h1', imageurl, type, true, '', mode, translations);
			$("h1_randomized").value = "1";
			random_count--;
		}
		if ($("h2_chosen").value == "0" || $("h2_randomized").value == "1") {
			if ($("h3_chosen").value == "0") empty++;
			if ($("p1_chosen").value == "0") empty++;
			if ($("p2_chosen").value == "0") empty++;
			if (empty == 1) mode = 2;
			if (random_count == 1) mode = 1;
			pick_random_player(url, 'h', 'h2', imageurl, type, true, '', mode, translations);
			$("h2_randomized").value = "1";
			random_count--;
		}
		if ($("h3_chosen").value == "0" || $("h3_randomized").value == "1") {
			if ($("p1_chosen").value == "0") empty++;
			if ($("p2_chosen").value == "0") empty++;
			if (empty == 1) mode = 2;
			if (random_count == 1) mode = 1;
			pick_random_player(url, 'h', 'h3', imageurl, type, true, '', mode, translations);
			$("h3_randomized").value = "1";
			random_count--;
		}
		if ($("p1_chosen").value == "0" || $("p1_randomized").value == "1") {
			mode = 2;
			if (random_count == 1) mode = 1;
			pick_random_player(url, 'p', 'p1', imageurl, type, true, '', mode, translations);
			$("p1_randomized").value = "1";
			random_count--;
		}
		if ($("p2_chosen").value == "0" || $("p2_randomized").value == "1") {
			pick_random_player(url, 'p', 'p2', imageurl, type, true, '', 1, translations);
			$("p2_randomized").value = "1";
		}
	}
}

function pick_random_player(url, pos, pos_full, imageurl, type, replace, favteam, mode, translations)
{
	// Remove player if already chosen, get player price and add it to saldo
	var player_value = 0;
	if (replace == true) {
		if ($(pos_full + "_chosen").value == "1") {
			player_value = parseSaldo("jersey_price_" + pos_full);
		}
	}

	// Get already selected id's so those are not selected again
	var selected_ids = '0';
	if ($("h1_chosen").value == "1") selected_ids = selected_ids+"_"+$("h1_player_id").value;
	if ($("h2_chosen").value == "1") selected_ids = selected_ids+"_"+$("h2_player_id").value;
	if ($("h3_chosen").value == "1") selected_ids = selected_ids+"_"+$("h3_player_id").value;
	if ($("p1_chosen").value == "1") selected_ids = selected_ids+"_"+$("p1_player_id").value;
	if ($("p2_chosen").value == "1") selected_ids = selected_ids+"_"+$("p2_player_id").value;
	if ($("m_chosen").value == "1") selected_ids = selected_ids+"_"+$("m_player_id").value;

	var saldo = parseSaldo('saldo') + player_value;
	var params = "pos="+pos+"&saldo="+saldo+"&favteam="+favteam+"&selected="+selected_ids+"&mode="+mode;
	var url2 = url+'?js=1&rand='+Math.random();
	
	var myAjax = new Ajax.Request(				 
		url2, 
		{
			asynchronous: false,
			method: 'get',
			parameters: params,
			onComplete: function(rsp) {
				if (rsp.responseText != "false") {
					player = rsp.responseText.evalJSON();
					if (player.player_id != "undefined") {
						// Remove player if present and replace is true
						if (replace == true) {
							if ($(pos_full + "_chosen").value == "1") {
								change_player_selection_status(pos_full, type, translations);
							}
						}
						// Choose new player
						choose_player(player.player_id, player.player_name, pos, formatThousand(player.current_value), player.smliiga_team, player.injury_status, type, imageurl, player.stats, translations, pos_full);
					}
				}
			}
		});
}

function change_playersearch_view(view, suffix)
{
	if (view == 'tagged')
	{	
		$("div_player_search_result" + suffix).style.display = 'none';
		$("search_view_link" + suffix).style.display = '';
		$("tagged_view_link" + suffix).style.display = 'none';
		$("player_position" + suffix).disabled = true;
		$("player_team" + suffix).disabled = true;
		$("player_value" + suffix).disabled = true;
		$("tagged_players_view" + suffix).style.display = '';
		playerselect_load_tagged_players('tagged_players_view' + suffix, '/team/taggedplayer');
	}
	else if (view == 'search')
	{	
		$("tagged_players_view" + suffix).style.display = 'none';
		$("div_player_search_result" + suffix).style.display = '';
		$("search_view_link" + suffix).style.display = 'none';
		$("tagged_view_link" + suffix).style.display = '';
		$("player_position" + suffix).disabled = false;
		$("player_team" + suffix).disabled = false;
		$("player_value" + suffix).disabled = false;
	}
}

function playerselect_load_tagged_players(div_id, url)
{
	var url2 = url+'?js=1&rand='+Math.random();	
	var tag_type = 'simple';
	if(div_id == 'tagged_players_view_advanced') tag_type = 'advanced'; 
	new Ajax.Updater(div_id, url2, {method: 'get', parameters: 'view=trades&ajax=1&tag_type=' + tag_type, onComplete: function() {change_osta_button_status();}});
}
