
/**********************************************************************
**GENERAL FUNCTIONS
----------------------------------------------------------------------------------------------------------*/
function elementbyid( id ) {
    if (document.getElementById)
        var returnVar = document.getElementById(id);
    else if (document.all)
        var returnVar = document.all[id];
    else if (document.layers)
        var returnVar = document.layers[id];
    return returnVar;
}

var eventsadded = new Array();

function addEvent(element, type, handler) {

	if(eventsadded[element+type+handler] == true) {
		alert(eventsadded[element+type+handler]);
		return true;
	}

    if (!handler.$$guid) handler.$$guid = addEvent.guid++;

    if (!element.events) element.events = {};



    var handlers = element.events[type];

    if (!handlers) {

        handlers = element.events[type] = {};



        if (element["on" + type]) {

            handlers[0] = element["on" + type];

        }

    }



    handlers[handler.$$guid] = handler;

    element["on" + type] = handleEvent;
	
	eventsadded[element] = true;

}



addEvent.guid = 1;



function removeEvent(element, type, handler) {



    if (element.events && element.events[type]) {

        delete element.events[type][handler.$$guid];
		
		eventsadded[element+type+handler] = false;

    }

};



function handleEvent(event) {



    event = event || window.event;

    var handlers = this.events[event.type];



    for (var i in handlers) {

        this.$$handleEvent = handlers[i];

        this.$$handleEvent(event);

    }

}


var goodbrowser = function() {
	if (typeof document.body.style.maxHeight != "undefined") {

	  return true;

	} else {

		return false;
	
	}
}

var get_random = function(number) {

    var ranNum= Math.floor(Math.random()*number);
	
    return ranNum;
	
}

var toggle_vis = function(id) {

	Effect.toggle(id,'blind');
	
}

var toggle_droplist = function() {

	Effect.toggle('gselect_series_list_top','appear');
	
	document.onclick = function() {
		if(elementbyid('gselect_series_list_top').style.display == 'none') return;
		else {
			return toggle_droplist();
		}
	}
	


}

var toggle_spoil = function(id) {

	toggle_vis(id);
	
    if(elementbyid(id+'m').value == 'Spoiler[+]') elementbyid(id+'m').value = 'Spoiler[-]';
    else elementbyid(id+'m').value = 'Spoiler[+]';
	
}

var pre_toogle_vis = function(id) {

	var cookie = readCookie('toogle_'+id);
	
	if(cookie == null) return true;
	elementbyid(id).style.display = cookie;
	
}

var dopopup = function(url) {

	return window.open(url,'',"width=470px,height=500px,status,scrollbars,resizable");
	
}

var ver_act = function(act_name) {

	if (confirm('Are you sure you want to '+act_name+'?')) {
	
		return true;
		
	} else {
	
		return false;
		
	}
	
}

var errFunc = function(t) {

    alert('Error ' + t.status + ' -- ' + t.statusText);
	
}

var handlerFunc = function(t) {

    alert(t.responseText);
	
}

var deletion = function(script_object, div_id){

	var confirm_delete = ver_act('delete '+div_id+' '+script_object);
	
	if (confirm_delete){
	
		var myAjax = new Ajax.Request(BASE_HREF+'user/delete.php', {asynchronous:true,method: 'post',postBody:'do='+div_id+'&id='+script_object,onSuccess:handlerFunc, onFailure:errFunc}); 
		
		var target = elementbyid(div_id+script_object);
		
		target.innerHTML = "<p class='ytag'>This "+div_id+" has been removed.</p>";
		
	} 
	
}

var update_alertbox = function(id,task) {

	if(task == 'insert') {
	
		scroll(0,0);
		
		var target = elementbyid('body');
		
		target.innerHTML = "<div id='_alertbox"+id+"' class='nw_box' style='height: 100px; min-height: 100px;'><div class='floatleft' style='width: 10%'><img src='"+BASE_HREF+"images/fns.chibi.png' alt='alertbox_chibi' /></div><div id='alertbox"+id+"' class='floatleft' style='width: 90%;'></div></div>"+target.innerHTML;
		
	} else {
	
		elementbyid("_alertbox"+id).style.display = 'none';
		
	}
	
	return true;
}

var addfavorite = function(type,id) {

	var upid = id+get_random(5)+get_random(10);
	
	update_alertbox(upid,'insert');
	
	new Ajax.Updater('alertbox'+upid, BASE_HREF+'clientscript/addfavorite.php?type=1&id='+id, {asynchronous:true, evalScripts:true});
	
	setTimeout("update_alertbox("+upid+",'')", 5000);
	
}
/**********************************************************************
**COOKIES
----------------------------------------------------------------------------------------------------------*/
function createCookie(name,value,days) {
	//can not be set to a global var
	if (days) {
	
		var date = new Date();
		
		date.setTime(date.getTime()+(days*24*60*60*1000));
		
		var expires = "; expires="+date.toGMTString();
		
	} else var expires = "";
	
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {

	var nameEQ = name + "=";
	
	var ca = document.cookie.split(';');
	
	for(var i=0;i < ca.length;i++) {
	
		var c = ca[i];
		
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
		
	}
	
	return null;
}

function eraseCookie(name) {

	createCookie(name,"",-1);
	
}

/**********************************************************************
** MANGA VIEWER FUNCTIONS
----------------------------------------------------------------------------------------------------------*/
var needed_src, mangaimageobject, mangaholder, manga_has_loaded_once;

var toggle_viewmethod = function(trigger_type) {

	var mangaviewmethod = readCookie('viewmethod');

	//Default to 1 (manual)
	if(mangaviewmethod == null) mangaviewmethod = 2;
	
	//Update to current
	if(trigger_type == 1) {
		if(mangaviewmethod == 1) {
			elementbyid('viewmethod').value = "View Method (Manual)";
		} else {
			elementbyid('viewmethod').value = "View Method (Auto)";
		}
		
		createCookie('viewmethod',mangaviewmethod,2);
		
		return;
	}
	
	//Change and update
	if(mangaviewmethod == 1) {
		elementbyid('viewmethod').value = "View Method (Auto)";
		createCookie('viewmethod',2,2);
	} else {
		elementbyid('viewmethod').value = "View Method (Manual)";
		createCookie('viewmethod',1,2);
	}
	
}


var any_scan = function(pick_any_scan) {

	update_scan(pick_any_scan);
	
}

var next_scan = function() {

	selected_scan = parseInt(selected_scan);
	
	if((selected_scan+1) > number_of_scans) return;
	else selected_scan += 1;
	
	update_scan(selected_scan);
}

var prev_scan = function() {

	selected_scan = parseInt(selected_scan);
	
	if(selected_scan-1 <= 0 ) return;
	else selected_scan -= 1;
	
	update_scan(selected_scan);
}

var go2chapter = function(method) {


	if(method == 0) {
	
		if(typeof(prevchapter) == "undefined") {
			selected_scan = number_of_scans;
		} else {
			window.location.href = BASE_HREF+'manga/'+prevchapter+'';
			return;
		}
	
	} else {
	
		if(typeof(nextchapter) == "undefined") {
			selected_scan = 1;
		} else {
			window.location.href = BASE_HREF+'manga/'+nextchapter+'';
			return;
		}
	
	}
	
	update_scan(selected_scan);

}

function update_scan(chosen_scan) {


	//Disable the prev and next buttons
	if(chosen_scan+1 > number_of_scans) {
		elementbyid('nextscan1').disabled = true;
		elementbyid('nextscan2').disabled = true;
	} else {
		elementbyid('nextscan1').disabled = false;
		elementbyid('nextscan2').disabled = false;
	}
	
	if(chosen_scan-1 <= 0) {
		elementbyid('prevscan1').disabled = true;
		elementbyid('prevscan2').disabled = true;
	} else {
		elementbyid('prevscan1').disabled = false;
		elementbyid('prevscan2').disabled = false;
	}
	
	
	//Determine the view method
	var mangaviewmethod = readCookie('viewmethod');
	if(mangaviewmethod == null) mangaviewmethod = 1;
	
	//The user is manual viewing. so send em to the "bookmark link" :)
	//Oh and make sure you don't send them away on first load. haha
	if(mangaviewmethod == 1 && manga_has_loaded_once == true && elementbyid('viewmethod') != undefined) {
		window.location.href = BASE_HREF+bookmarklink+"/pg"+chosen_scan;
		return;
	} else {
		manga_has_loaded_once = true;
	}

	
	//Set selected scan
	selected_scan = chosen_scan;
	
	//Update the bookmark link
	if(mangaviewmethod == 2)
	elementbyid('bookmarklink').innerHTML = "<a href='"+BASE_HREF+bookmarklink+"/pg"+chosen_scan+"'><strong>Click me before you bookmark this page!</strong></a>";
	
	//Set the new scan and such
	if(elementbyid('loadingscan')) {
	
		mangaholder = elementbyid('scanholder');

		if(chosen_scan == 0) {
		
			mangaholder.innerHTML = "No scan has been selected.";
			
		} else {

			//Set the drop down menu
			elementbyid('scan_select').selectedIndex = elementbyid('scan_select2').selectedIndex = selected_scan-1;
			
			//Note that the scan is loading
			elementbyid('loadingscan').innerHTML = "<img alt='Loading...' title='Loading...' src='"+BASE_HREF+"bin/1/images/icons/loading.gif' />";

			//Update the image to the site
			mangaholder.innerHTML = "<img src='"+scans[selected_scan]+"' title='Click for next' alt='Scan' onload='update_scan1()' onclick='next_scan()' />";

		}
	}
}

var update_scan1 = function() {

	//Done loading, so change the image
	elementbyid('loadingscan').innerHTML = "";
	
	if(selected_scan+1 > number_of_scans) return;
	
	var newimage = new Image; 
	
	newimage.src = scans[selected_scan+1]; 

}

function kpressed_IE(e) {
    if (!e) var e = window.event;
    if (e.keyCode) {
        keycode = e.keyCode;
        if ((keycode == 39) || (keycode == 37)) {
            window.event.keyCode = 0;
        }
    } else {
        keycode = e.which;
    }
    if (keycode == 39) {
        next_scan();
        return false;
    } else if (keycode == 37) {
		prev_scan();
        return false;
    }
}
function kpressed_others(e) {
    if (e.which) {
        keycode = e.which;
    } else {
        keycode = e.keyCode;
    }
	if (keycode == 39) {
        next_scan();
        return false;
    } else if (keycode == 37) {
		prev_scan();
        return false;
    }
}

var himg = function(needed_src) {

	scroll(0,0);
	
	var fsi = elementbyid('FULL_SIZE_IMAGE');
		
	fsi.style.display = 'block';

	fsi.innerHTML = "<img src='"+needed_src+"' alt='' class='full_size' id='full_zoom_scan' />";

	addEvent(fsi, 'click', hideHIMG);
	
}

var hideHIMG = function() {

	elementbyid('FULL_SIZE_IMAGE').style.display = 'none';
	elementbyid('FULL_SIZE_IMAGE').innerHTML = '';
	removeEvent(elementbyid('FULL_SIZE_IMAGE'), 'click', hideHIMG);
	
}

/**********************************************************************
** BBCODE FUNCTIONS
----------------------------------------------------------------------------------------------------------*/
var BBCode = function(){

	window.undefined = window.undefined;
	
	this.initDone = false;
	
}

BBCode.prototype.init = function(t){

	if(this.initDone) return false;
	
	if(t == undefined) return false;
	
	this._target = t ? elementbyid(t) : t;
	
	this.initDone = true;
	
	return true;
	
}

BBCode.prototype.noForm = function(){

	return this._target == undefined;
	
}
// insertcode is used for bold, italic, underline and quote and just
// wraps the tags around a selection or prompts the user for some
// text to apply the tag to
BBCode.prototype.insertCode = function (tag, desc, endtag) {

	if(this.noForm()) return false;
	
	var isDesc = (desc == undefined || desc == '') ? false : true;
	
	// our textfield
	var textarea = this._target;
	
	// our open tag
	var open = '['+tag+']';
	
	var close = '[/'+((endtag == undefined) ? tag : endtag)+']';
	
	if (!textarea.setSelectionRange) {
	
		var selected = document.selection.createRange().text;
		
		if (selected.length<=0) {
		
			// no text was selected so prompt the user for some text
			textarea.value += open+((isDesc) ? prompt("Please enter the text you'd like to "+desc, "")+close : '');
			
		} else {
		
			// put the code around the selected text
			document.selection.createRange().text = open+selected+((isDesc) ? close : '');
			
		}
	} else {
	
		// the text before the selection
		var pretext = textarea.value.substring(0, textarea.selectionStart);
		
		// the selected text with tags before and after
		var codetext = open+textarea.value.substring(textarea.selectionStart, textarea.selectionEnd)+((isDesc) ? close : '');
		
		// the text after the selection
		var posttext = textarea.value.substring(textarea.selectionEnd, textarea.value.length);
		
		// check if there was a selection
		if (codetext == open+close) {
		
			//prompt the user
			codetext = ((isDesc) ? prompt("Please enter the text you'd like to "+desc, "") : '');
			
			if(codetext != null) {
			
				codetext = open+codetext+close;
				
			} else {
			
				return false;
				
			}
			
		}

		// update the text field
		textarea.value = pretext+codetext+posttext;
		
	}
	
	// set the focus on the text field
	textarea.focus();
}

//insertstring is used for emoticons
// sends basic text to the form-nothing more
BBCode.prototype.insertString = function (string) {

	if(this.noForm()) return false;
	
	// our textfield
	var textarea = this._target;
	
	// the text before the selection
	var pretext = textarea.value.substring(0, textarea.selectionStart);
	
	// the text after the selection
	var posttext = textarea.value.substring(textarea.selectionEnd, textarea.value.length);
	
	//put down the text
	textarea.value = pretext+' '+string+' '+posttext;
	
	// set the focus on the text field
	textarea.focus();
	
}

// inserts an image by prompting the user for the url
BBCode.prototype.insertImage = function (html) {

	if(this.noForm()) return false;
	
	var src = prompt('Please enter the url', 'http://');
	
	this.insertCode('img='+src);
	
}

// inserts a link by prompting the user for a url
BBCode.prototype.insertLink = function (html) {

	if(this.noForm()) return false;
	
	this.insertCode('url='+prompt("Please enter the url", "http://"), 'as text of the link', 'url');
	
} 

// inserts a quote by prompting the user for a url
BBCode.prototype.insertQuote = function (html) {

	if(this.noForm()) return false;
	
	var q = prompt("Please enter the quote user", "");
	
	this.insertCode('quote'+((q == null) ? '' : '='+q), 'for the quote', 'quote');
	
} 

//Insert quote
BBCode.prototype.insertFullquote = function(author) {

	if(this.noForm()) return false;
	
	var textarea = this._target;
	
	var pretext = textarea.value.substring(0, textarea.selectionStart);
	
	var posttext = textarea.value.substring(textarea.selectionEnd, textarea.value.length);
	
    var message = elementbyid('quoteholder');
	
	textarea.value = pretext+"[quote"+((author != null) ? '='+author : '')+"]"+message.innerHTML+"[/quote]"+posttext;
	
	// set the focus on the text field
	textarea.focus();
	
}

BBCode.prototype.requestQuote = function(id,type,author) {

    new Ajax.Updater('quoteholder', BASE_HREF+'user/getpost.php?do=plain_'+type+'&id='+id, {asynchronous:false, evalScripts:true});
	
    this.insertFullquote(author);
	
}

var poll_select_option = new Array();

var updatepoll = function(pid) {

	if(typeof poll_select_option[pid] == "undefined") poll_select_option[pid] = 0;
	
	new Ajax.Updater('requestpoll', BASE_HREF+"clientscript/poll.php?id="+pid+"&option="+poll_select_option[pid], {asynchronous:true, evalScripts:false,
		onComplete: function(transport) {
			new Effect.Highlight('requestpoll', {startcolor:'#fff773', endcolor:'#ffffff'})
		}
	});
	
}

var showing_mangatxt = 0;

var editmanga_img = function(seriesid) {

	if(showing_mangatxt == 1) {
		elementbyid('editmanga_txt').innerHTML = '';
		showing_mangatxt = 0;
		return;
	}

	new Ajax.Updater('editmanga_txt', BASE_HREF+'submit/updateseries.php?id='+seriesid+'&method=1', {asynchronous:true, evalScripts:false,
		onComplete: function(transport) {
		
			new Effect.Highlight('editmanga_txt', {startcolor:'#fff773', endcolor:'#ffffff'});
			
			showing_mangatxt = 1;

		}
	});

}

var editmanga_txt = function(seriesid) {

	if(showing_mangatxt == 2) {
		elementbyid('editmanga_txt').innerHTML = '';
		showing_mangatxt = 0;
		return;
	}

	new Ajax.Updater('editmanga_txt', BASE_HREF+'submit/updateseries.php?id='+seriesid, {asynchronous:true, evalScripts:false,
		onComplete: function(transport) {
		
			new Effect.Highlight('editmanga_txt', {startcolor:'#fff773', endcolor:'#ffffff'});
			
			showing_mangatxt = 2;

		}
	});

}

var featload = 0;

var load_gallery = function(seriesid,type) {

	if(featload == 1) {
		elementbyid('featload').innerHTML = '';
		featload = 0;
		return;
	}

	new Ajax.Updater('featload', BASE_HREF+'clientscript/gallery.php?id='+seriesid+'&type='+type, {asynchronous:true, evalScripts:false,
		onComplete: function(transport) {
		
			new Effect.Highlight('featload', {startcolor:'#fff773', endcolor:'#ffffff'});
			
			featload = 1;

		}
	});

}

function doupload() {

	var uploadbutton = document.getElementById('uploadbutton');
	uploadbutton.style.display = 'none';
	
	var uploadbutton = document.getElementById('imgload');
	uploadbutton.style.display = 'inline';
	
	document._uploadform.submit();

}

function doedit(form,seriesid,method) {
	var uploadbutton = document.getElementById('editform');
	uploadbutton.style.display = 'none';
	
	var uploadbutton = document.getElementById('editcom');
	uploadbutton.style.display = 'inline';
	
	new Ajax.Request(BASE_HREF+"submit/updateseries.php?id="+seriesid+"&method="+method, {asynchronous:true, parameters:Form.serialize(form)});
	return false;
}


var load_ajax_comments = function(page_num) {
	
	if(typeof com_method == "undefined") return true;
	
	new Ajax.Updater('comment_field', BASE_HREF+'clientscript/getcomments.php?method='+com_method+'&parent='+com_get_set+'&page='+page_num, {asynchronous:true, evalScripts:false,
		onComplete: function(transport) {
			new Effect.Highlight('comment_field', {startcolor:'#ff99ff', endcolor:'#999999'})
		}
	});
	
}

var alreadyfetchingshouts = false;

var fetch_shouts = function() {

	if(alreadyfetchingshouts == true) {
		return;
	}
	
	alreadyfetchingshouts = true;

	elementbyid('shoutprogress').style.display = 'block';

	new Ajax.Updater('shouts', BASE_HREF+'clientscript/shouts.php', {asynchronous:true, evalScripts:false,
		onComplete: function(transport) {
		
			new Effect.Highlight('shouts', {startcolor:'#fff773', endcolor:'#ffffff'})
			
			elementbyid('shoutprogress').style.display = 'none';
			
			alreadyfetchingshouts = false;
		}
	});

}

var quick_comment = function(id,field) {

	//Get the inserted text
	var text = elementbyid(field).value;
	
	if(id > 0) {
	
		var button = elementbyid('mcsubmit');
		var method = com_method;
		var b4text = '';
		
	} else {
	
		var button = elementbyid('sbsubmit');
		var method = 'shoutbox';
		var b4text = elementbyid('shoutbox_name').value;
		text = b4text+':_:-:'+text;
		
	}

	//See if this text is valid
	if(text == '') {
	
		alert("You didn't enter anything!");
		
		return;
		
	}
	
	button.disabled = true;
	
	//Attempt to make the post
	new Ajax.Request(BASE_HREF+'clientscript/addcomment.php?method='+method+'&id='+id+'&data='+encodeURIComponent(text), {
	
	  onComplete: function(transport) {
	    if (200 == transport.status) {
			
			if(transport.responseText == 'success') {
				
				if(id > 0) {
				
					if(elementbyid('commentcount')) {
					
						var comcount = elementbyid('commentcount');
					
						comcount.innerHTML = parseInt(1 + comcount.innerHTML);
				
					}
				
					load_ajax_comments(1);
				
					alert("Your new comment has been added!");
				
				} else {
				
					fetch_shouts();
				
				}
				
				elementbyid('sbtarea').innerHTML = "<textarea id='shoutbox_txt'></textarea>";
			
			} else {
		
				alert(transport.responseText);
				
			}
			
			button.disabled = false;
		}
	  }
	  
	});
}


var dorate = function(amount,id,type) {
	
	var stars = elementbyid('ratestars');
	
	stars.style.display = 'none';

	//Input the rating
	new Ajax.Request(BASE_HREF+'clientscript/dorate.php?method='+com_method+'&id='+id+'&amount='+amount, {
	
	  onComplete: function(transport) {
	  
	    if (200 == transport.status) {
			
			if(transport.responseText == 'success') {
			
				//Fugire out the number of ratings for far
				rating_num = rating_num + 1;

				var newrating = ( ( rating_total + amount ) / rating_num );
				
				//Update the stars

				staramount = Math.round(newrating);
				
				resetstars();
				
				stars.style.display = 'inline';
				
				//Update the stars to reflect the new result
				
				alert("Thanks for rating!");
				
				elementbyid('ratenote').innerHTML = rating_num+" ratings";
				
			
			
			} else {
			
				stars.style.display = 'inline';
		
				alert(transport.responseText);
				
			}
		}
		
	  }
	  
	});
}


var resetstars = function() {

	if(typeof staramount == "undefined") return true;
	
	//Preload the active star image incase there are no stars
	if (typeof activestar == 'undefined') {
		activestar = new Image;
		activestar.src = BASE_HREF+'images/ratefull.png';
	}
	
	//Reset the stars
	rateimage(staramount,2);
}

var rateimage = function(amount,method) {

	var rnote = elementbyid('ratenote');
	
	if(method == 1) {
		
		if(amount == 1) rnote.innerHTML = "Waste of time...";
		else if(amount == 2) rnote.innerHTML = "Nothing special...";
		else if(amount == 3) rnote.innerHTML = "Worth Reading.";
		else if(amount == 4) rnote.innerHTML = "Enjoyable?";
		else rnote.innerHTML = "Epic!";
	
	} else {
		rnote.innerHTML = rating_num+" ratings";
	}
	
	for(var i = -99; i <= 1; i++) {}
	
	for(var i = 1; i <= 5; i++) {
	
		var thisstar = elementbyid('ratestar'+i);
		
		if(!thisstar) continue;
	
		if(i <= amount)
			thisstar.src = BASE_HREF+'images/ratefull.png';
		else 
			thisstar.src = BASE_HREF+'images/rateempty.png';
		
	}

}
/**********************************************************************
** PM FUNCTIONS
----------------------------------------------------------------------------------------------------------*/
var del_msg = function(script_object){

	confirm_delete = ver_act('delete private message');
	
	if (confirm_delete){
	
		var myAjax = new Ajax.Request(BASE_HREF+'user/personal_message.php', {asynchronous:true,method: 'post',postBody:'do=delete&id='+script_object,onSuccess:handlerFunc, onFailure:errFunc}); 
		
		target = elementbyid('pm_'+script_object);
		
		target.innerHTML = "";
		
	} 
	
}
var req_msg = function(id) {

	var xtarget = elementbyid('justread'+id);
	
	if(msg_is_open[id] != 1 && msg_is_open[id] != 2) {
	
		new Ajax.Updater('viewpm'+id, BASE_HREF+'user/personal_message.php?do=view&id='+id, {asynchronous:true, evalScripts:true});
		
	} else {
	
		toggle_vis('viewpm'+id);
		
	}
	
	if(msg_is_open[id] != 2) {
	
		xtarget.innerHTML = "<span style='padding-left:30px;font-size:120%;'><b><em>just read</em></b></span>";
		
		msg_is_open[id] = 2;
		
	} else {
	
		xtarget.innerHTML = "<span style='padding-left:30px;font-size:120%;'><b><em>just closed</em></b></span>";
		
		msg_is_open[id] = 1;
		
	}
	
}