//***************************************************************************//
//  Copyright (c) 2010 The galaxySMS Group                                   //
//  All rights reserved.                                                     //
//                                                                           //
//  This file is part of galaxySMS.                                          //
//                                                                           //
//  galaxySMS is free software: you can redistribute it and/or modify        //
//  it under the terms of the GNU General Public License as published by     //
//  the Free Software Foundation, either version 2 of the License, or        //
//  (at your option) any later version.                                      //
//                                                                           //
//  galaxySMS is distributed in the hope that it will be useful,             //
//  but WITHOUT ANY WARRANTY; without even the implied warranty of           //
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the            //
//  GNU General Public License for more details.                             //
//                                                                           //
//  You should have received a copy of the GNU General Public License        //
//  along with galaxySMS.  If not, see <http://www.gnu.org/licenses/>.       //
//***************************************************************************//
function countdown()
{
	var d = new Date();
	var target_s = new Date("23 Oct "+d.getFullYear()+" 00:00 UTC-0400");
	var currtime = parseInt(d.getTime()/1000);
	var target = parseInt(target_s.getTime()/1000);
	var interval = target - currtime;

	if (interval <= 0)
		gE('countdown').innerHTML = "NCFC is on right now!";
	else 
	{
		var secs = Math.floor(interval % 60);
		var mins = Math.floor(interval / 60 % 60);
		var hrs = Math.floor(interval / 3600 % 24);
		var days = Math.floor(interval / 86400);
		var months = Math.floor(days / 30);
		gE('countdown').innerHTML = (months > 2 ? months + " months, " + (days%30) + " day"+((days % 30) == 1 ? "" : "s")+", " : days + " day"+(days == 1 ? "" : "s")+", ") + hrs + " hour"+(hrs == 1 ? "" : "s") + ", " + mins + " minute"+(mins == 1 ? "" : "s")+(days < 7 ? ", " + secs + " second"+(secs == 1 ? " " : "s ") : " ")+"to go.";
	}

	setTimeout(countdown, 1000);
}
var table_order = "";
// Table reshuffling
function tableOrder(id)
{
	$(".draggable").css("cursor", "move");
	$("#"+id).tableDnD({
		onDragClass: 'rowdragging',
	    onDrop: function(table, row) {
			table_order = $.tableDnD.serialize();
		},
			/*
			var rows = table.tBodies[0].rows;
            for (var i=0; i<rows.length; i++) {
                tableorder[i] = row.id;
            }
	    },*/
		dragHandle: 'draggable'
	});
}
function setOrder(act, tableid, elemid)
{
	var order = table_order;
	if (order == "") return;
	order = order.replace(new RegExp(tableid, "gi"), "order");
	externalPage("admincp", act+"&"+order, elemid, undefined, true, 'nopad');
}

// AJAX stuff
function externalPage(page, act, elemid, complete, force, nothrob)
{
	// FIXME: debug
	var cacheblock =  "&"+(new Date()).getTime();

	if (!$("#"+elemid).hasClass('loaded') || force != undefined)
	{
		if (nothrob == undefined)
			$("#"+elemid).html("<div style='padding:16px;text-align:center;'><img src='script/loading.gif' /></div>");
		else if (nothrob == 'nopad')
			$("#"+elemid).html("<img src='script/loading.gif' />");
			
		if (complete == undefined)
			$("#"+elemid).load("ajaxlatch.php?page="+page+".ajax.php&act="+act+cacheblock);
		else
			$("#"+elemid).load("ajaxlatch.php?page="+page+".ajax.php&act="+act+cacheblock, complete);
		$("#"+elemid).addClass('loaded');
	}
}

// TODO: Control panels and other pages with menus send you back to the right page

// Instant error-checking script - we do some simple client-side checking before
// sending it to the server for scrutinizing
// All admin CP sections
function checkACP(secname)
{
	var form, errs = [];
	switch (secname)
	{
		case 'mimetypes':
			form = document.mimetypes;
			// Check for mime
			if (form.mime.value.indexOf("/") < 1)
				errs.push(lang['mimeinvalid']);
			// Check for filetypes
			if (!form.filetypes.value.match(/^[A-z]*$/) || form.filetypes.value == '')
				errs.push(lang['filetypeinvalid']);
		break;
	}
	// Are there errors?
	if (errs.length > 0) {
		showErrors(errs);
		return false;
	}
	// Nope!
	return true;
}
// Registration page
function checkUCP()
{
	var errs = [];
	var form = document.usercp;
	// Is old password filled?
	if (form.oldpass.value == '' && form.password.value != '')
		errs.push(lang['oldpwblank']);
	// Do the passwords match?
	if (form.password.value != form.password2.value)
		errs.push(lang['pwnomatch']);
	// Is the email filled in?
	if (form.email.value == '')
		errs.push(lang['emailblank']);
	else if (!(/\b[A-Z0-9._%+-]+@(?:[A-Z0-9-]+\.)+[A-Z]{2,6}\b/i.test(form.email.value)))
		errs.push(lang['emailinvalid'])
	// MSN sanity check
	if (!(/\b[A-Z0-9._%+-]+@(?:[A-Z0-9-]+\.)+[A-Z]{2,6}\b/i.test(form.msn.value)) && form.msn.value != '')
		errs.push(lang['msninvalid']);
	// ICQ sanity check
	if (!(/^[1-9][0-9]*$/.test(form.icq.value)) && form.icq.value != 0 && form.icq.value != '')
		errs.push(lang['icqinvalid']);
	// TODO: Website check
	
	// Are there errors?
	if (errs.length > 0) {
		showErrors(errs);
		return false;
	}
	// Nope!
	return true;
}

// Registration page
function checkReg()
{
	var errs = [];
	var form = document.register;
	// Is username filled?
	if (form.username.value == '')
		errs.push(lang['unblank']);
	// Is password & password2 filled?
	if (form.password.value == '')
		errs.push(lang['pwblank']);
	else if (form.password2.value == '')
		errs.push(lang['pw2blank']);
	// Do they match?
	else if (form.password.value != form.password2.value)
		errs.push(lang['pwnomatch']);
	// Is the email filled in?
	if (form.email.value == '')
		errs.push(lang['emailblank']);
	else if (!(/\b[A-Z0-9._%+-]+@(?:[A-Z0-9-]+\.)+[A-Z]{2,6}\b/i.test(form.email.value)))
		errs.push(lang['emailinvalid'])
	// Are there errors?
	if (errs.length > 0) {
		showErrors(errs);
		return false;
	}
	// Nope!
	return true;
}

// Login page
function checkLogin() 
{
	var errs = [];
	var form = document.login;
	// Is username filled?
	if (form.username.value == '')
		errs.push(lang['unblank']);
	// Is password filled?
	if (form.password.value == '')
		errs.push(lang['pwblank']);
	// Are there errors?
	if (errs.length > 0) {
		showErrors(errs);
		return false;
	}
	// Nope!
	return true;
}

// Show errors
function showErrors(errs, ignoreh) {
	if (!$('#errblock').hasClass("hidden") && ignoreh == undefined) {
		$('#errblock').slideUp();
		setTimeout(showErrors, 400, errs, true);
	}
	else {
		$('#errs').html("");
		for (var i in errs)
			$('#errs').html($('#errs').html()+"&middot; "+errs[i]+"<br />");
		$('#errblock').removeClass("hidden").hide().slideDown();
	}
}

// Numeros only!
function numbersPls(elem, floatpls)
{
	if (floatpls == undefined)
	{
		if (!elem.value.match(/^(?:[0-9]*)$/g))
		{
			elem.value = parseInt(elem.value);
			alert(lang['numberplease']);
		}
	}
	else
		if (!elem.value.match(/^(?:[0-9]*(|\.)[0-9]*)$/g))
		{
			elem.value = parseFloat(elem.value);
			alert(lang['numberplease']);
		}
}
// Toggle an element. The second argument is optional, setting it will hide the
// calling element. It must be set to 'this', not 'true' or 'false'.
function toggle(elem, self) 
{
	if (self != undefined)
		$(self).slideUp(400);
		
	if($('#'+elem).is(':visible'))
		$('#'+elem).fadeOut(400);
	else
		$('#'+elem).slideToggle(400);
};

// Shows "x characters remaining" for a textarea. It should be inside a div.
function updateChars(maxlen, self) {
	// TODO: Un-stub
};

// Extend a textarea
function extendT(elem) {
	$('#'+elem).rows += 5;
};
// Contracts a textarea
function contractT(elem) {
	elem = $('#'+elem);
	elem.rows -= 5;
	if (elem.rows < 5)
		elem.rows = 5;
};

// Prevent "enter" from submitting (should be used in onKeyDown)
function blockEnter(ev) 
{
	var kcode = (document.all) ? event.keyCode : (ev.which || ev.keyCode);
	return (kcode != 13);
};

// Menus
// TODO: change menu header
function menuInit() 
{
	$(".menuitem").hide();
	$(".menuactive").show();
	try
	{
		if (script_do != undefined)
		{
			// FIXME: Very unprofessional way of doing this.
			// Scavenge the menus...
			$(".menubutton a").each(function()
			{
				if ($(this).parent().html().indexOf("'"+script_do+"'") != -1)
				{
					// Got it!
					var attr = $(this).attr("onClick");
					eval(attr); // FIXME: EVAL!!! ARGH!!!
					return false; //break
				}
			});
		}
	}
	catch (err){}
}
function showMenu(menuname, elem, fake, notrans) 
{
	if (notrans == undefined)
	{
		$(".menuactive").removeClass("menuactive").addClass("menuitem").slideUp(200);
		$("#"+menuname).removeClass("menuitem").addClass("menuactive").delay(200).slideDown(200);
	}
	else
	{
		$(".menuactive").removeClass("menuactive").addClass("menuitem").hide();
		$("#"+menuname).removeClass("menuitem").addClass("menuactive").show();
	}
	if (fake == undefined)
	{
		$(".menuselected").removeClass("menuselected");
		$(elem).parent().addClass("menuselected");
	}
}
function showMenuExt(menuname, page, elem, complete, otheract, specificelem, force)
{
	showMenu((specificelem == undefined ? menuname : specificelem), elem, otheract, otheract);
	externalPage(page, menuname+(otheract == undefined ? "" : "&"+otheract), (specificelem == undefined ? menuname : specificelem), complete, force, otheract);
	if (otheract != undefined)
		elem.parentNode.innerHTML = "<img src='script/loading.gif' />";
}
// Set the above to all input type=text and input type=password
function applyBlock() 
{
	$("input[type*=text]").each(function() 
	{
		this.onkeypress=blockEnter;
	});
	$("input[type*=password]").each(function() 
	{
		this.onkeypress=blockEnter;
	});
};

// TODO: Cutetime 
// TODO: Port ACP permissions from CTBBS

// Check all checkboxes of the same name
function checkAll(name) 
{
	$("input[name*="+name+"]").each(function() 
	{
		$(this).attr('checked', 'checked');
	});
};
// Unchecks all checkboxes of the same name
function uncheckAll(name) {
	$("input[name*="+name+"]").each(function() 
	{
		$(this).attr('checked', '');
	});
};
// Toggles all checkboxes of the same name
function checkAll(name) 
{
	$("input[name*="+name+"]").each(function() 
	{
		if ($(this).attr('checked') == true)
			$(this).attr('checked', '');
		else
			$(this).attr('checked', 'checked');
	});
};

// Applies a BBCode
function applyBBCode(bbcode, elem) 
{
	var msgbox = $("#"+elem);
	var segments = [bbcode.substring(0,bbcode.indexOf("|")), bbcode.substring(bbcode.indexOf("|")+1, bbcode.length)];
	// IE Hacky Fix... Useless browser doesn't provide a way to get the START POINT OF THE SELECTION, yet you
	// can get the size of the selection in pixels... Oh well, suffer if you're using IE. Enjoy Char's crappy hack.
	if (document.selection) 
	{
		msgbox.focus();
		document.selection.createRange().text = segments[0] + document.selection.createRange().text + segments[1];
		document.selection.empty();
	}
	 // Sane Mozilla/Webkit etc method
	else if (msgbox.selectionStart == msgbox.selectionEnd) 
	{
		msgbox.focus();
		var pos = msgbox.value.substring(0,msgbox.selectionStart).length + segments[0].length;
		msgbox.value = msgbox.value.substring(0,msgbox.selectionStart) + segments[0] + segments[1] + msgbox.value.substring(msgbox.selectionEnd, msgbox.value.length);
		msgbox.setSelectionRange(pos,pos);
	}
	// Wrap it (Mozilla/Webkit style)
	else 
	{
		msgbox.focus();
		var pos = msgbox.value.substring(0,msgbox.selectionStart).length + segments[0].length + msgbox.value.substring(msgbox.selectionStart, msgbox.selectionEnd).length + segments[1].length;
		msgbox.value = msgbox.value.substring(0,msgbox.selectionStart) + segments[0] + msgbox.value.substring(msgbox.selectionStart, msgbox.selectionEnd) + segments[1] + msgbox.value.substring(msgbox.selectionEnd, msgbox.value.length);
		msgbox.setSelectionRange(pos,pos);
	}

}
// Sets the BBCode Helpline
function setHelpline(elem, text) 
{
	if (text == undefined || text == "")
		text = "If text is selected, the BBCode will be wrapped around it.";
	$('#'+elem).text(text);
}

//Previews booth descriptions
function loadBoothInfo()
{
	// Booth mouse over functions
	/*$(".booth_image").mouseover(function()
	{
		$(this).parents(".booth").find(".booth_desc").show();
	});
	$(".booth_image").mouseout(function()
	{
		$(this).parents(".booth").find(".booth_desc").hide();
	});*/
}
//document.getElementById shortcut
function gE(elem)
{
	return document.getElementById(elem);
}

// Page load function
function pageLoad()
{
	var outer = $($(".bars").parents("table").get(0)).width();
	var inner = $(".bars").width() % 40;
	$($(".bars").parents("table").get(0)).width(outer - inner);
}

function showHide(elem)
{
	var e; e = gE(elem);
	if(e.style.display == 'none')
	{
		e.style.display = 'block';
	}
	else
	{
		e.style.display = 'none';
	}
}

function editBoothImageToggle(mode)
{
	showHide('image_inputs');
	showHide('preloaded_image');
	if(mode == 0)
	{
		gE('newimage').value='';
	}
	else
	{
		gE('image_file').setAttribute('type', 'input'); //Reset the contents
		gE('image_file').setAttribute('type', 'file');
		gE('newimage').value = 'na';
	}
}

//Workshop time tables query for workshop registration. Queries an ajax page.
function workshopLoadTables(mode,workshopid)
{
	if (window.XMLHttpRequest){// code for IE7+, Firefox, Chrome, Opera, Safari
		xmlhttp=new XMLHttpRequest();
	}
	else{// code for IE6, IE5
		xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
	}
	gE('time_tables_div').innerHTML = "<span style='font-size:20px; font-weight:bold;'>Loading time table . . . </span>";
	//Ajax code. 
	xmlhttp.onreadystatechange=function(){
		//If the state and status are okay
		if (xmlhttp.readyState==4 && xmlhttp.status==200){
			//Get the response text
			var response_text = xmlhttp.responseText;
			gE('time_tables_div').innerHTML = response_text;
			
			if(mode == "edit")
			{ 
				//when editing, the ajax script returns some additional data for the processing.
				var to_split = gE('ajax_javascript').value.split("-"); //Split the js
				window.selected_array = to_split[0].split("|"); //First goes to the window array. This is just a basic array of the values
				window.selected_count = window.selected_array.length-1;
				gE('ws_time_data').value = to_split[1]; //Second goes to the time data.
			}
		}
	}
	//Get the stored variables
	params = 'day='+gE('ws_day').value+"&mode="+mode;
	if(mode == "edit")
	{
		params = params+"&workshop="+workshopid;
	}
	xmlhttp.open("POST","ajaxlatch.php?page=workshops.fetch_times.ajax.php",true);
	xmlhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
	xmlhttp.setRequestHeader('Content-length',params.length);
	xmlhttp.send(params);
}

//Function for highlighting/clicking processing. Mode 0 = highlight, mode 1 = un-highlight, mode 2 = click
function workshopsHoverCheck(div,mode){
	var t_length = parseInt(gE('ws_duration').value)+1; //length of chosen slot
	var TIME_MAX = 47; //Max time slot
	var can_go,div_number; //can_go = boolean to occupy slot, div_number = current slot's div number
	can_go = true;
	div_number = parseInt(div.id.substr(10,2),10); //Get the div number from the id
	var i; i = 0;//CHECK FOR CLICKABILITY/HOVERABLENESS
	if( mode === 0 || mode==2){
		for(i = 0; i<t_length; i+=1){//Loop ahead by t_length
			if(div_number+i>TIME_MAX){ //If out of range, can't go
				can_go = false;
				break;
			}
			else{
				var td_class;	td_class = gE('time_cell_'+(div_number+i)).className; //Get the class name of the current cell being examined.
				//var td_class = gE('time_cell_'+(div_number+i)).className; //Get the class name of the current cell being examined.
				if(div_number+i<=TIME_MAX){ //If it's within the maximum cells
					if( td_class == 'time_cell_full' || td_class == 'time_cell_hover_full'){ //If one of the slots is occupied
						can_go = false; //Then it can't be clicked
						break;
					}
				}
			}
		}
		i = 0;
	}
	//Check to clear the previously clicked cells, on a click
	if(mode == 2){
		for(i = 0; i<window.selected_count; i+=1){ 
			gE(window.selected_array[i]).setAttribute("class",'time_cell_empty');
			gE(window.selected_array[i]).setAttribute("className",'time_cell_empty');
		}
		window.selected_count = 0;
		gE('ws_time_data').value='';
	}
	i = 0; //Loop to actually set the cell classes
	for(i = 0; i<t_length; i+=1){ 
		if(div_number+i<=TIME_MAX){ //If within the range
			//Get the class and element
			var element = gE('time_cell_'+(div_number+i));
			var t_class; t_class = element.className;
			var final_class = t_class;
			if(mode === 0){ //If mode is 0, set the appropriate cells to be selected. This is hover mode.
				if(can_go){ //If the area is clickable, then it's either hovering blankly, or over a selected spot
					if(t_class == 'time_cell_empty'){ final_class = "time_cell_hover"; }
					else{ final_class='time_cell_selected_hover'; }
				}
				else{ //Otherwise if it can't be clicked, then the cell should be of the negative class if not over a blocked slot, or of the hover-full class
					if( (t_class == 'time_cell_hover' || t_class=='time_cell_empty') ){ final_class = 'time_cell_hover_negative'; }
					else if( t_class == 'time_cell_full') { final_class = 'time_cell_hover_full'; }
					else { final_class='time_cell_selected_negative'; }
				}
			}
			else if(mode==1){ //Unhover "reset" mode
				if(t_class == 'time_cell_full' || t_class == 'time_cell_hover_full'){ final_class = 'time_cell_full'; }
				else if(t_class!="time_cell_selected_hover" && t_class!='time_cell_selected' && t_class!='time_cell_selected_negative'){
					final_class = 'time_cell_empty';
				}
				else{ final_class='time_cell_selected'; }
			}
			else{ //Clicken mode.
				if(can_go){
					window.selected_array[i] = element.id;
					window.selected_count+=1;
					final_class='time_cell_selected';
				}
				else{ break; }
			}
			gE('time_cell_'+(div_number+i)).setAttribute('class',final_class);
			gE('time_cell_'+(div_number+i)).setAttribute('className',final_class); //Set the attribute
		}
		
		if(mode==2)
		{
			gE('ws_time_data').value = div_number;
		}
	}
}

function designBooth_addMoreScreens() //Adds more of the screenshot uploaders in the design booth page
{
	//alert(image_count);
	if(image_count<IMAGE_MAX)
	{
		div = gE('image_inputs');
		div.innerHTML ="<input type='file' name='image_file"+image_count+"' id='image_file"+image_count+"'/>\n<a style='margin:0px; padding:0px;' id='image_inputs'></a>";
		div.id='';
		image_count+=1;
		gE('image_number').value=image_count;
	}
	if(image_count>=IMAGE_MAX)
	{
		gE('js_add_more_screens').style.display = 'none';
	}
}

function designBooth_changeImage(num)
{
	gE('img_preview'+num).innerHTML = "<input type='file' name='image_file"+num+"' id='image_file"+num+"'/>";
}

function designBooth_deleteScreen(num)
{
	gE('img_preview'+num).innerHTML='';
	IMAGE_MAX+=1;
}

function designBooth_deleteGame()
{
	var gname,index;
	gname = gE('preview_game').value;
	index =  gname.indexOf("|delete");
	if(index==-1)
	{
		gE('preview_game').value+="|delete";
		gE('game_icon').src="theme/default/images/zipped_folder_delete.png";
		gE('delete_link').innerHTML = "Keep";
	}
	else
	{
		gE('preview_game').value = gname.substring(0,index);
		gE('game_icon').src="theme/default/images/zipped_folder.png";
		gE('delete_link').innerHTML = "Delete";
	}
}

function designBooth_changeGame()
{
	gE("game_forms").innerHTML = "<div id='game_upload_form' ><input type='file' name='game_file' id='game_file'/></div><div id='game_link_form' style='display:none;'><input type='text' name='game_url' value=''/></div><a href=\"javascript:showHide('game_upload_form'); showHide('game_link_form')\">Switch between link and upload.</a><input type='hidden' name='preview_game_name' value='-1'/>";
}

function confirmDelete(page,type)
{
	if(confirm("Are you sure you want to delete this "+type+"? This action is permanent and cannot be undone!"))
	{
		window.location = page;
	}
}

function imagePopUp(img) {
	//Get the original dimensions
	var newImg = new Image();
	newImg.src = gE(img).src; 
	var width = newImg.width+1;
	var height = newImg.height+1;
	//Close the popup if it exists
	if(popup!=false)
	{
		popup.close();
		popup = false;
	}
	if(width == 1)
	{
		width = 400;
		height = 400;
	}
	//Popup again
	popup=window.open('','image','toolbar=0, location=0, directories=0, menuBar=0, scrollbars=0, resizable=0, width='+width+', height='+height);
	popup.document.clear();
	popup.document.write("<html><head><title>Image</title></head><body style='padding:0; background:#000000; margin:0;'><center><img style='border:none;' src='"+newImg.src+"'/></center></body></html>");
	popup.focus();
	popup.document.close();
	
};  

//Radio querying functions
function loadRadioInfo()
{
	if (window.XMLHttpRequest){// code for IE7+, Firefox, Chrome, Opera, Safari
		xmlhttp=new XMLHttpRequest();
	}
	else{// code for IE6, IE5
		xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
	}
	gE('radio_info').innerHTML = "		<a href='http://www.shouthostdirect.com/startpage/index.php?ip=67.159.45.120&port=8292'  target='_blank'>NCFC Radio</a> &middot; <span class='small'>Status: <img src='theme/default/images/radiowaiting.gif' style='vertical-align:middle;'/> Loading. . .</span><br/><span style='font-size:10px;'><i>(May Contain Offensive Language)</i></span>"
	//Ajax code. 
	xmlhttp.onreadystatechange=function(){
		//If the state and status are okay
		if (xmlhttp.readyState==4 && xmlhttp.status==200){
			//Get the response text
			var response_text = xmlhttp.responseText;
			to_split = response_text.split("<%%>");
			gE('radio_info').innerHTML = to_split[0];
			//gE('header_radio_status').src = to_split[1];
		}
	}
	//Set
	params = '';
	xmlhttp.open("POST","script/set_radio_info.ajax.php",true);
	xmlhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
	xmlhttp.setRequestHeader('Content-length',params.length);
	xmlhttp.send(params);
	t=setTimeout("loadRadioInfo()",30*1000); //Refresh every 30 seconds
}
