var currentDate = new Date()
var cur_year = currentDate.getYear();
var cur_month = currentDate.getMonth();
var days_data = [];
var tournaments_data = [];
var cur_day_id = 0;

function daysInMonth(iMonth, iYear) {
	return 32 - new Date(iYear, iMonth, 32).getDate();
}

//*** update days data
function update_calendar() {
//test change
	if (dgbi('pc_calendar_box') == undefined) return;
	dgbi('cal-days').style.display = 'none';
	dgbi('calendar_loading').style.display  = 'block';
	ajaxObj = new XMLHTTP("/ajax_servers/calendar.php");
	ajaxObj.debug = 0;
	ajaxObj.call("month="+cur_month+"&year="+cur_year, update_calendar_callback);
}
function update_calendar_callback(days) {
	days_data = days;
	draw_calendar();
}
//*** draw calendar
function draw_calendar() {
	clear_calendar();
	dgbi('calendar_loading').style.display = 'none';
	dgbi('cal-days').style.display = 'block';
	days = daysInMonth(cur_month, cur_year);
	dgbi('calendarDataLabel').innerHTML = get_datestring(cur_month, cur_year);
    var date =new Date().getDate();

    for (i=1; i<=days; ++i) {
		var new_day = document.createElement('span');
		new_day.id = 'day'+i;
        var className = 'pc_pokerDay';
        if(cur_month == new Date().getMonth())
          className =  i!=date?'pc_pokerDay':'pc_pokerDay_c';
        new_day.className = className;
		if (days_data[i] != null) {
			tournaments = days_data[i];
			have_freerols = 0; have_tourneys = 0;  have_offline = 0;
			for (j=0; j<tournaments.length; ++j) {
				if (tournaments[j].type == 0) { have_freerols = 1;}
				else if (tournaments[j].type == 1) { have_tourneys = 1; }
				else if (tournaments[j].type == 2) { have_offline = 1; }
			}
			if (have_freerols == 1 && have_tourneys == 1 && have_offline == 1) {
				new_day.className = className +' tfo';
			}
			if (have_freerols == 1 && have_tourneys == 1 && have_offline == 0) {
				new_day.className = className +' tf';				
			}
			if (have_freerols == 1 && have_tourneys == 0 && have_offline == 1) {
				new_day.className = className +' fo';
			}
			if (have_freerols == 1 && have_tourneys == 0 && have_offline == 0) {
				new_day.className = className +' f';
			}			
			if (have_freerols == 0 && have_tourneys == 1 && have_offline == 1) {
				new_day.className = className +' to';
			}
			if (have_freerols == 0 && have_tourneys == 1 && have_offline == 0) {
				new_day.className = className +' t';
			}
			if (have_freerols == 0 && have_tourneys == 0 && have_offline == 1) {
				new_day.className = className +' o';
			}
			
		}
		new_day.onmouseover = show_popup;
        new_day.onmouseout = closeHandler;

        new_day.innerHTML = i;
        document.getElementById('cal-days').appendChild(new_day);
	}
}
function get_day_coords(element) {
	var E = {x:0,y:0};
  var B = element;
  while (B) {
    E.x += B.offsetLeft;
    E.y += B.offsetTop;
    B = B.offsetParent;
 }
 return E;
}
function my_GetClientW()
{
	return(document.body && (typeof(document.body.clientWidth) != tt_u) ? document.body.clientWidth
			: (typeof(window.innerWidth) != tt_u) ? window.innerWidth
			: tt_db ? (tt_db.clientWidth || 0)
			: 0);
}
function show_popup() {
	id = this.id;
	id = id.replace('day', '');
	cur_day_id = id;
    date = new Date(cur_year,cur_month,id);
    dgbi('calpop-container').style.display = 'none';
	dgbi('pc_popup_date').innerHTML = month_names[cur_month]+', '+id + ', ' + days_names[date.getDay()+1];

	if (days_data[id] != null) {
		coords = get_day_coords(this);
		//doc_width = document.body.parentNode.scrollWidth;
		doc_width =  my_GetClientW();
		if (doc_width > 1000) {
			delta = (doc_width - 1000) / 2;
		} else {
			delta = 0;
		}
		new_left = (coords.x-delta);
		if (new_left + 400 >= doc_width) new_left -= 240;
		dgbi('calpop-container').style.top = (coords.y+15)+'px';
		dgbi('calpop-container').style.left = new_left+'px';
		//add data
		clear_popup();
		data = days_data[id];
		for (i=0; i<data.length; ++i) {
			var new_item = create_popup_item(data[i]);
			dgbi('popup_cont').appendChild(new_item);
		}
		dgbi('calpop-container').style.display = 'block';
    }
}

function create_popup_item(tourney) {
	new_item = document.createElement('div');
	new_item.className = 'pc_callpop';


	heading_box = document.createElement('div');
	heading_box.className = 'pc_titlebox';

	img_box = document.createElement('div');
	img_box.className = 'pc_rimg';
	img = document.createElement('img');
	img.className = 'pc_rlogo';
	img.src = "/images/pc/"+tourney.room_id+".png";
	img_box.appendChild(img);
	title_box = document.createElement('div');
	title_box.className = 'pc_ttile';
	heading = document.createElement('h3');
	heading.appendChild(document.createTextNode(tourney.title));
	title_box.appendChild(heading);
	heading_box.appendChild(img_box);
	heading_box.appendChild(title_box);
	new_item.appendChild(heading_box);

	p_list = document.createElement('ul');
	p_list.className = 'cal-items';
	if (tourney.game != '' && tourney.game != null) {
		p_list.appendChild(add_pc_list_value(pc_str_game, tourney.game));
	}
	if (tourney.buyin != '' && tourney.buyin != null) {
		p_list.appendChild(add_pc_list_value(pc_str_buyiun, tourney.buyin));
	}
	if (tourney.max_players != '' && tourney.max_players != null && tourney.max_players != 0) {
		p_list.appendChild(add_pc_list_value(pc_str_players, tourney.max_players));
	}
	if (tourney.start_date != '' && tourney.start_date != null && tourney.start_date != 0) {
		p_list.appendChild(add_pc_list_value(pc_str_starts, tourney.start_date));
	}
	new_item.appendChild(p_list);

	btn_div = document.createElement('div');
	btn_div.className = 'pc_btn';
	if (tourney.registered != null) {
		btn_div.appendChild(document.createTextNode(pc_str_registered));
	} else {
		btn_img = document.createElement('img');
		btn_img.src = pc_btn_url;
		btn_img.room_id = tourney.room_id;
		btn_img.t_id = tourney.id;
		if (tourney.unregistered != undefined) {
			btn_img.onclick = show_only_registered;
		} else {
			btn_img.onclick = register_from_pc;
		}
		btn_div.appendChild(btn_img);
	}
	new_item.appendChild(btn_div);

	return new_item;
}

function add_pc_list_value(val_name, val_value) {
	el = document.createElement('li');
	sp_name = document.createElement('span');
	sp_name.className = 'pc_name';
	sp_name.innerHTML = val_name+':';
	el.appendChild(sp_name);

	sp_val = document.createElement('span');
	sp_val.className = 'pc_val';
	sp_val.innerHTML = ' '+val_value;
	el.appendChild(sp_val);
	return el;
}

function clear_calendar() {
	days_container = document.getElementById('cal-days');
  while (days_container.childNodes.length >0 ) {
		days_container.removeChild( days_container.childNodes[0] );
	}
}

function clear_popup() {
	days_container = document.getElementById('popup_cont');
	while (days_container.childNodes.length >0 ) {
		days_container.removeChild( days_container.childNodes[0] );
	}
}

function decrementMonth() {
	work_year = (cur_year < 1900) ? cur_year + 1900 : cur_year;
	current = new Date(work_year, cur_month-1, 1);
	cur_year = current.getYear();
	cur_month = current.getMonth();
	//dgbi('calendarDataLabel').innerHTML = get_datestring(current);
	update_calendar();
}

function incrementMonth() {
	work_year = (cur_year < 1900) ? cur_year + 1900 : cur_year;
	current = new Date(work_year, cur_month+1, 1);
	cur_year = current.getYear();
	cur_month = current.getMonth();
	update_calendar();
}
function get_datestring(month, year) {
	if (year < 1900) { year += 1900;}
	month_str = month_names[month];
    
    return month_str+', '+year;
}

function pc_popup_close() {
	dgbi('calpop-container').style.display = 'none';
}

function goto_all_tournaments() {
	window.location.href = '/tournaments.html?d='+cur_day_id+'&m='+cur_month+'&y='+cur_year;
}

function fetch_tournaments() {
	dgbi('tournaments_list_box').style.display = 'none';
	dgbi('tournaments_loading').style.display = 'block';
	ajaxObj = new XMLHTTP("/ajax_servers/tournaments.php");
	ajaxObj.debug = 0;
	ajaxObj.call("type="+dgbi('t_filter_type').value+"&room="+dgbi('t_filter_room').value+'&game='+dgbi('t_filter_game').value+'&starts='+dgbi('t_filter_starts').value, fetch_tournaments_callback);
}

function fetch_tournaments_callback(resp) {
	tournaments_data = resp;
    my_table = dgbi('tournaments_list');
	while (my_table.childNodes.length >0 ) {
			my_table.removeChild( my_table.childNodes[0] );
	}
	my_tbody = create_heading()
	my_table.appendChild( my_tbody );
	//adding data
	for (i=0; i<tournaments_data.length; ++i) {
		my_tbody.appendChild(add_row(tournaments_data[i]));
	}
	dgbi('tournaments_loading').style.display = 'none';
	dgbi('tournaments_list_box').style.display = 'block';
}
function create_heading() {
	heading = document.createElement('tbody');
	new_item = document.createElement('tr');

	title = document.createElement('th');
	title.appendChild(document.createTextNode(pc_str_room));
	new_item.appendChild(title);

	title = document.createElement('th');
	title.appendChild(document.createTextNode(pc_str_title));
	new_item.appendChild(title);

	title = document.createElement('th');
	title.appendChild(document.createTextNode(pc_str_game));
    title.setAttribute("nowrap","");
    new_item.appendChild(title);

	title = document.createElement('th');
	title.appendChild(document.createTextNode(pc_str_buyiun));
	new_item.appendChild(title);


	title = document.createElement('th');
	title.appendChild(document.createTextNode(pc_str_starts));
	new_item.appendChild(title);

	title = document.createElement('th');
	title.appendChild(document.createTextNode(pc_str_players));
	new_item.appendChild(title);

	heading.appendChild(new_item);
	return heading;
}
function add_row(t) {
	new_item = document.createElement('tr');

	logo = document.createElement('td');
	img = document.createElement('img');
	img.src = "/images/pc/"+t.room_id+".png";
	logo.appendChild(img);
	new_item.appendChild(logo);

	title = document.createElement('td');
	if (t.description != '') {
		btn_img = document.createElement('img');
		btn_img.src = '/images/information.png';
		btn_img.description = t.description;
		btn_img.onmouseover = show_tourney_tip;
		btn_img.className = 'tourney_moreinfo';
		title.appendChild(btn_img);
	}
	title.appendChild(document.createTextNode(t.title));
	title.style.width = '220px';
	new_item.appendChild(title);

	game = document.createElement('td');
	game.appendChild(document.createTextNode(t.game))
	new_item.appendChild(game);

	buyin = document.createElement('td');
	buyin.appendChild(document.createTextNode(t.buyin))
    buyin.setAttribute("style","text-align: center;");
    new_item.appendChild(buyin);

	starts = document.createElement('td');
	starts.appendChild(document.createTextNode(t.start_date))
	new_item.appendChild(starts);

	players = document.createElement('td');
	if (t.max_players == '0') t.max_players = ' ';
	players.appendChild(document.createTextNode(t.max_players))
	new_item.appendChild(players);

	do_reg = document.createElement('td');
	do_reg.className = 'td_reg';
	if (t.registered != null ) {
		do_reg.appendChild(document.createTextNode(pc_str_registered));
	} else {
		btn_img = document.createElement('img');
		btn_img.src = pc_btn_url;
		btn_img.room_id = t.room_id;
		btn_img.t_id = t.room_tourneyid;
		if (t.unregistered != undefined) {
			btn_img.onclick = show_only_registered;
		} else {
			btn_img.onclick = register_from_pc;
		}
		do_reg.appendChild(btn_img);
	}
	new_item.appendChild(do_reg);

	return new_item;
}

function register_me(el, room_id, t_id) {
	ajaxObj = new XMLHTTP("/ajax_servers/tourney_register.php");
	ajaxObj.debug=0;
	ajaxObj.call("room_id="+room_id+"&t_id="+t_id, do_nothing);
	my_parent = el.parentNode;
	while (my_parent.childNodes.length >0 ) {
		my_parent.removeChild( my_parent.childNodes[0] );
	}
	my_parent.appendChild(document.createTextNode(pc_str_registered));
}

function register_from_pc() {
	r_id = this.room_id;
	t_id = this.t_id;
	ajaxObj = new XMLHTTP("/ajax_servers/tourney_register.php");
	ajaxObj.debug=0;
	ajaxObj.call("room_id="+r_id+"&t_id="+t_id, do_nothing);
	my_parent = this.parentNode;
	while (my_parent.childNodes.length >0 ) {
		my_parent.removeChild( my_parent.childNodes[0] );
	}
	my_parent.appendChild(document.createTextNode(pc_str_registered));

	for (i=0; i<=31; ++i) {
		if (days_data[i] != null) {
			for (j=0; j<days_data[i].length; ++j) {
				if (days_data[i][j].room_id == r_id && days_data[i][j].room_tourneyid == t_id) {
						days_data[i][j].registered = 1;
						break;
				}
			}
		}
	}
}

function show_tourney_tip() {
	desc = this.description;
	Tip(desc, WIDTH, 300, DELAY, 50);
}

function closeHandler(evt) {
    var id;
    evt = (evt) ? evt : ((window.event) ? event : null);
    if (evt) {
        var elem = (evt.target) ? evt.target : ((evt.srcElement) ?
            evt.srcElement : null);
        if (elem) {
             // limit processing to element nodes
             if (elem.nodeType == 1) {
                // for W3C DOM property
                if (evt.relatedTarget) {
                    if (evt.relatedTarget != elem.firstChild) {
                        id = evt.relatedTarget.id;
                    }
                // for IE DOM property
                } else if (evt.toElement) {
                    id = event.toElement.id
                }
            }
        }
       if(id!="calpop-inner")
         pc_popup_close()
    }
}

/**** sharkscope section ****/
function search_shark() {
	name = dgbi('shark_player_name').value;
	network = dgbi('shark_networkId').value;
    type = dgbi('shark_type').value;
    dgbi('shark_error_1').style.display = 'none';
	dgbi('shark_error_ajax').style.display = 'none';
	dgbi('shark_graph').style.display = 'none';

	dgbi('shark_data').innerHTML = '';
	if (name == '') {
		dgbi('shark_error_1').style.display = 'block';
		return;
	}
  dgbi('shark_results').style.display = 'none';
  dgbi('shark_loading').style.display = 'block';

	ajaxObj = new XMLHTTP("/ajax_servers/sharkscope.php");
	ajaxObj.debug = 0;
	ajaxObj.call("nick="+name+"&network="+network+"&type="+type, sharkscoper_callback);
}

function sharkscoper_callback(resp) {
    var shark_data = resp;

	if (shark_data.searches_left != undefined && dgbi('shark_searches_left') != undefined)  {
		dgbi('shark_searches_left').innerHTML = shark_data.searches_left;
	}

	if (shark_data.err != '')  {
		dgbi('shark_error_ajax').innerHTML = shark_data.err;
		dgbi('shark_error_ajax').style.display = 'block';
	}

	if (shark_data.stats != undefined) {
			if (shark_data.stats.stats == 'notfound') {
					str_res = 'Player not found.';
				} else {
					if (shark_data.stats.stats == 'dataclosed') {
						str_res = 'Data for this player is closed.';
					} else {
						dgbi("sharkGames").innerHTML = shark_data.stats.stats.games;
						dgbi("shark_avg_profit").innerHTML = shark_data.stats.stats.avg_profit + "$";
            dgbi("shark_avg_profit").style.color = shark_data.stats.stats.avg_profit >0 ?"#669c0f":"#a55021";
            dgbi("shark_avg_stake").innerHTML =shark_data.stats.stats.avg_stake + "$";
						dgbi("shark_roi").innerHTML = shark_data.stats.stats.avg_roi + "%";
            dgbi("shark_roi").style.color = shark_data.stats.stats.avg_roi >0 ?"#669c0f":"#a55021";

            dgbi("shark_profit").innerHTML =shark_data.stats.stats.total_profit + "$";
            dgbi("shark_profit").style.color = shark_data.stats.stats.total_profit >0 ?"#669c0f":"#a55021";
            dgbi('shark_graph_img').src = '/cache/sharkscope/'+shark_data.stats.key+'_roi.png?cached='+Math.random();
            dgbi('shark_graph_img').onload = function(){
                dgbi('shark_loading').style.display = 'none';
                dgbi('shark_results').style.display = 'block';
                dgbi('shark_graph').style.display = 'block';
            };
            return;
           }
	     }
	  dgbi('shark_data').innerHTML  = str_res;
      dgbi('shark_loading').style.display = 'none';
      dgbi('shark_results').style.display = 'block';  
    }
}
