/**
 * onArcade 2.4.0
 * Copyright © 2006-2011 Hans Mäesalu & Eveterm OÜ, All Rights Reserved
 **
 * ONARCADE IS NOT FREE SOFTWARE!
 * http://www.onarcade.com
 **/

// register AJAX error handler
$(document).ajaxError(function(e, xhr, settings, exception) {
	if (xhr.readyState == 0) {
		return;
	}
	alert(settings.url + " returned error:\n"+ exception);
});

// create new DOM object
$.createElement = function(element) {
	return jQuery(document.createElement(element));
};

$.tmpl = function(template, data, returnString) {
	// make replacements
	if (data != undefined) {
		if (data.length === 0) {
			return returnString ? "" : $();
		} else if (data[0]) {
			var fullTemplate = "";
			var newTemplate = "";
			for (var i in data) {
				newTemplate = template;
				for (var j in data[i]) {
					newTemplate = newTemplate.replace(new RegExp("\\$\\("+ j +"\\)","g"), data[i][j]);
				}
				fullTemplate += newTemplate;
			}
			template = fullTemplate;
		} else {
			for (var i in data) {
				template = template.replace(new RegExp("\\$\\("+ i +"\\)","g"), data[i]);
			}
		}
	}

	if (typeof(returnString) == "object") {
		// append to object
		returnString.append(template);
		return;
	} else if (returnString == true) {
		// return string
		return template;
	}

	// return jQuery object
	return $(template);
};

//sometimes we just need <br />
function nl2br(string) {
	return string.replace(/(\\r)?\\n/g, "<br />");
}

// check if object is empty
function is_empty(object) {
	for (i in object) {
		return false;
	}
	return true;
}

//we do not want HTML
function nohtml(string) {
    string = string.replace(/"/g,'&quot;');
    string = string.replace(/</g,'&lt;');
    string = string.replace(/>/g,'&gt;');
	return string;
}

//remove letters from field ID/name, to get only ID
function field_number(field_id) {
	return parseInt(field_id.replace(/[^0-9]/g,""));
}

//(un)check all checkboxes
function check_all(checkbox) {
	checkbox = $(checkbox);
	var checked = $(checkbox).is(":checked");
	checkbox.closest("form").find("input[type='checkbox']").each(function() {
		$(this).attr("checked", checked);
	});
}

//some thins shouldn't be deleted just because user thinks they should be deleted
function confirm_delete() {
	return (confirm(lang.sure_delete) ? true : false);
}

//AJAX loader image
var loader = {
	url: siteurl + "images/load.gif",
	replace: function(object) {
		// make sure we have jQuery object
		if (typeof(object) == "string") {
			object = $("#" + object);
		} else if (!object.jQuery) {
			object = $(object);
		}

		// get contents height
		var margin = (object.height() - 16) / 2;
		if (margin < 0) {
			margin = 0;
		}

		// insert loader
		object.html('<div class="center"><img src="' + loader.url + '" style="width: 16px; height:16px; margin: ' + margin + 'px 0px;" /></div>');
	},
	insert: function(object) {
		if (typeof(object) == "string") {
			object = $("#" + object);
		}

		// loader image
		var loader_img = object.next();
		if (loader_img.size() > 0 && loader_img.hasClass("loader")) {
			loader_img.show();
		} else {
			loader_img = $.createElement("img")
						.attr("src", loader.url)
						.addClass("loader")
						.insertAfter(object);
		}

		// disable button
		if (object.get(0).nodeName.toLowerCase() == "input") {
			object.attr("disabled", true);
		}
	},
	appendTo: function(object) {
		if (typeof(object) == "string") {
			object = $("#" + object);
		}
		object.append('<div class="center loader"><img src="'+ loader.url +'" alt="" /></div>');
	},
	remove: function(object) {
		if (typeof(object) == "string") {
			object = $("#" + object);
		}

		// loader image
		var loader_img = object.next();
		if (loader_img.size() > 0 && loader_img.hasClass("loader")) {
			loader_img.hide();
		}

		// enable button
		if (object.get(0).nodeName.toLowerCase() == "input") {
			object.attr("disabled", false);
		}
	}
};

//show AJAX error message
var error = {
	insert: function(message, object, options) {
		if (typeof(object) == "string") {
			object = $("#" + object);
		}
		if (options == undefined) {
			options = [];
		}

		// try to find an existing element
		if (options.after) {
			if (object.next().size() > 0 && (object.next().hasClass("error") || object.next().hasClass("error_green"))) {
				var errorr = object.next();
			}
		} else {
			if (object.prev().size() > 0 && (object.prev().hasClass("error") || object.prev().hasClass("error_green"))) {
				var errorr = object.prev();
			}
		}

		// insert new error element
		if (errorr == undefined) {
			var errorr = $.createElement("div");
			if (options.after) {
				errorr.insertAfter(object);
			} else {
				errorr.insertBefore(object);
			}
		}

		// update field info

		errorr.attr("class", (options.error == false ? "error_green":"error"));
		errorr.text(message);

		// slide down animation
		errorr.hide();
		errorr.slideDown(250);

		// hide after some time
		if (options.error == false && options.hide) {
			errorr.delay(1000 * options.hide).slideUp(250);
		}
	}
};

//work with hash in URL (value must be integer... for now)
var url_hash = {
	set_hash: function(variable, value) {
		var hashs = ""+location.hash;
		if (hashs.length == 0 || hashs == "#") {
			location.hash = variable + "/" + value;
		} else {
			var find_hash = hashs.match(new RegExp("(#|^|/)" + variable + "/[0-9]+"));
			if (find_hash != null) {
				location.hash = hashs.replace(""+find_hash[0], "" +find_hash[1] + variable + "/" + value);
			} else {
				location.hash += "/" + variable + "/" + value;
			}
		}
	},
	get_hash: function(variable) {
		var hashs = ""+location.hash;
		var find_hash = hashs.match(new RegExp("(#|^|/)" + variable + "/([0-9]+)"));
		if (find_hash == null) {
			return null;
		} else {
			return parseInt(find_hash[2]);
		}
	}
};

// image verification
var image_verification = {
	image_url: siteurl + "includes/verification_image.php",
	refresh_image: siteurl + "images/reload.png",
	// reload verification image
	refresh: function() {
		$(this).prev().attr("src", image_verification.image_url + "?" +  Math.random());
	},
	// attache verification image
	attach: function(element_id) {
		var parent_element = $("#" + element_id);
		if (parent_element.size() == 0) {
			return;
		}

		// already exists, just reload
		if (parent_element.children("div.image_verification").size() > 0) {
			parent_element.find("img.refresh_image").click();
			return;
		}

		var main_element = $.createElement("div").addClass("image_verification");
		$.createElement("img").attr("src", image_verification.image_url).addClass("code_image")
			.appendTo(main_element);
		$.createElement("img").attr("src", image_verification.refresh_image).addClass("refresh_image")
			.appendTo(main_element).click(image_verification.refresh);
		$.createElement("input").attr({type: "text", maxlength: 4, "name": "image_verification"}).addClass("small")
			.appendTo(main_element);

		parent_element.append(main_element);
	}
};

// user information menu menues
var menu = {

	a: [],
	bubble: [],

	init: function() {
		menu.a["favorites"] = $("#favourites_link").click("favorites", menu.open);
		menu.a["notifications"] = $("#notifications").click("notifications", menu.open);
	},

	create_bubble: function(type) {
		menu.bubble[type] = $.createElement("div").addClass("bubble").attr("id", type +"_menu")
									.html('<div></div>'
											+'<div class="bubble_up"></div>')
									.click(function(e) { e.stopPropagation(); })
									.appendTo($(document.body));

		if (type == "notifications") {
			menu.bubble[type].delegate(".del_notification", "click", menu.notification_delete);
		}
	},

	open: function(e) {
		e.preventDefault();
		e.stopPropagation();
		$(document).click();
		var type = e.data;

		if (menu.bubble[type] == null) {
			menu.create_bubble(type);
		}

		var pos = menu.a[type].offset();
		menu.bubble[type].show()
			.css({left: (pos.left - 5) +"px", top: (pos.top + 22) + "px"});

		loader.replace(menu.bubble[type].children("div").first());

		menu["load_"+ type]();

		$(document).one("click", function(e) {
			menu.bubble[type].hide();
		});
	},

	load_favorites: function() {
		$.getJSON(siteurl + "usercp.php?a=get_favorites&ajax=1", function(data) {
			var contents = menu.bubble["favorites"].children("div").first().empty();
			if (data.error) {
				contents.html(data.message);
				return;
			}
			$.tmpl(template.favorites_menu, data,
					contents);
		});
	},

	load_notifications: function() {
		$.getJSON(siteurl + "usercp.php?a=notifications&ajax=1", function(data) {
			var contents = menu.bubble["notifications"].children("div").first().empty();
			if (data.error) {
				contents.html(data.message);
				return;
			}

			for (var i in data.notifications) {
				data.notifications[i].siteurl = siteurl;
			}

			$.tmpl(template.notification_menu, data.notifications
					, contents);

			contents.append('<a href="'+ siteurl +'usercp.php#to_notifications" class="load_more">'+ data.all_notifications +'</a>');
		});
	},

	notification_delete: function(e) {
		e.preventDefault();
		var div_notification = $(this).closest(".notification");
		$.getJSON(siteurl + "usercp.php?a=notifications&ajax=delete&id="+ field_number(div_notification.attr("id")), function(data) {
			if (data.error) {
				alert(data.message);
				return;
			}
			div_notification.remove();
		});
	}
};
$(document).ready(menu.init);

// manage tab menus
function tab_menu(tabs_id, contents_id) {
	this.tabs_id = tabs_id;
	this.contents_id = contents_id;

	this.div;
	this.ul;

	this.tab = []; // tabs
	this.content = []; // contents of the tabs
	this.tab_functions = []; // onclick functions are here

	this.initiating = false; // true if tab is just being initiated

	// get content of tab (0, 1, 2...)
	this.get_content = function(i) {
		return this.content.eq(i);
	};

	// get tab (0, 1, 2...)
	this.get_tab = function(i) {
		return this.tab.eq(i);
	};

	// process tab opening (maybe run some extra functions)
	this.click_tab = function(tab) {
		var tab_id = parseInt(tab.data("id"));

		this.tab.removeClass("selected");
		tab.addClass("selected");

		this.content.hide();
		this.content.eq(tab_id).show();
		this.content.eq(tab_id).children(".error,.error_green").hide(); // hide old error messages

		// hash
		if (url_hash.get_hash(this.tabs_id) != null || tab_id > 0) {
			url_hash.set_hash(this.tabs_id, (tab_id + 1));
		}

		// run functions
		if (this.tab_functions[tab_id] != undefined) {
			for (i in this.tab_functions[tab_id]) {
				this.tab_functions[tab_id][i](tab_id);
			}
		}
	};

	// add action to be run when tab is opened
	this.add_action = function(tab_number, new_action) {
		if (this.tab_functions[tab_number] != undefined) {
			this.tab_functions[tab_number].push(new_action);
		} else {
			this.tab_functions[tab_number] = [new_action];
		}
	};

	// initiate tab menu
	this.init = function() {
		var here = this;

		this.ul = $("#" + this.tabs_id);
		if (this.contents_id == undefined) {
			this.div = this.ul.nextAll("div:first");
		} else {
			this.div = $("#" + this.contents_id);
		}

		// remove text in between
		this.ul.html(this.ul.html().replace(/\s*(<li)/ig, "$1"));

		// get tabs
		this.tab = this.ul.find("li>a");
		this.content = this.div.children("div").hide();

		// have to have as many tabs as tabs contents
		if (this.tab.size() != this.content.size()) {
			window.alert("ERROR! Tabs and contents not equal.");
			return;
		}

		// add tab IDs and events
		this.tab.each(function(i) {
			$(this).data("id", i).click(function(event, init) {
				here.initiation = (init != undefined && init == true);
				here.initiating = (init != undefined && init == true);
				here.click_tab($(this));
				return false;
			});
		});

		// get open tab ID
		var open_tab = 0;
		var hash_id = url_hash.get_hash(this.tabs_id);
		if (hash_id != null) {
			hash_id--;
			if (hash_id < this.tab.size()) {
				open_tab = hash_id;
			}
		}

		this.tab.eq(open_tab).trigger("click", [true]);
	};
}

// files scroller on index page
var scroller = {
	files: [],
	width: 70,
	height: 59,
	size: 0,
	moving: false,

	scroller: null,
	scroller_width: 0,
	ul: null,
	ul_width: 0,
	title: null,
	active: null,

	interval: null,
	current_offset: 0,
	goal_offset: 0,

	// show file title
	show_title: function(e) {
		// create element
		if (scroller.title == null) {
			scroller.title = $.createElement("div").addClass("title")
				.click(function() { scroller.active.click(); })
				.appendTo(scroller.scroller);
		}
		scroller.title.show();
		scroller.active = $(this);
		scroller.title.text(scroller.active.attr("alt"));

		// title position
		var x_post = e.pageX - scroller.scroller.offset().left - (scroller.title.width() / 2);
		if (x_post < 0) {
			x_post = 0;
		}
		scroller.title.css("left", x_post + "px");
	},
	hide_title: function() {
		if (scroller.title != null) {
			scroller.title.hide();
		}
	},
	// mouse moved
	mouse_move: function(event) {
		var x_pos = event.pageX - scroller.scroller.offset().left;
		scroller.goal_offset = (x_pos * ((scroller.ul_width - scroller.scroller_width) / scroller.scroller_width));
		if (!scroller.moving) {
			scroller.start_move();
		}
	},
	// go to address
	go_to: function(event) {
		window.location = event.data;
	},
	// build scroller
	build_list: function() {
		scroller.ul = $.createElement("ul");

		var li, a;
		for (i in scroller.files) {
			li = $.createElement("li");

			$.createElement("img").attr("src", scroller.files[i][2]).width(scroller.width).height(scroller.height)
				.attr("alt", scroller.files[i][0]).mouseenter(scroller.show_title)
				.bind("click", scroller.files[i][1], scroller.go_to)
				.appendTo(li);

			li.appendTo(scroller.ul);
		}
		scroller.ul.appendTo(scroller.scroller);

		scroller.scroller_width = scroller.scroller.width();
		scroller.ul_width = li.outerWidth() * scroller.size;
		scroller.ul.width(scroller.ul_width);

		scroller.scroller.mouseleave(scroller.hide_title)
			.mousemove(scroller.mouse_move);
	},
	// start movement
	start_move: function() {
		scroller.interval = setInterval(scroller.move, 10);
		scroller.moving = true;
	},
	// stop movement
	stop_move: function() {
		clearInterval(scroller.interval);
		scroller.moving = false;
	},
	// move scroller
	move: function() {
		if (scroller.current_offset != scroller.goal_offset) {
			var diff = scroller.goal_offset - scroller.current_offset;
			var change = diff / 25;
			if (diff > 0) {
				if (change < 1) {
					change = 1;
				}
				scroller.current_offset += change;
				if (scroller.current_offset > scroller.goal_offset) {
					scroller.current_offset = scroller.goal_offset;

					scroller.stop_move();
				}
			} else {
				if (change > -1) {
					change = -1;
				}
				scroller.current_offset += change;
				if (scroller.current_offset < scroller.goal_offset) {
					scroller.current_offset = scroller.goal_offset;

					scroller.stop_move();
				}
			}
			scroller.ul.css("left", "-" + scroller.current_offset + "px");
		}
	},
	init: function(width, height) {
		if (scroller.files.length == 0) {
			return;
		}

		scroller.scroller = $("#scroller");
		scroller.width = width;
		scroller.height = height;
		scroller.size = this.files.length;

		scroller.build_list();
	}
};

//count hits out
function link_out(link_id) {
	window.open(siteurl + "/links.php?a=out&id=" + link_id);
	return false;
}

// rate file
var rate_file = {

	// star events
	hover: function() {
		$(this).nextAll(".star").andSelf().addClass("star_hover");
	},
	clear: function() {
		$(this).parent().children(".star").removeClass("star_hover");
	},
	// submit new rating
	submit: function(e) {
		e.preventDefault();
		var element = $(this).parent();
		loader.insert(element.children(".star").last());
		$.post(siteurl + "/file.php?f=" + element.data("file_id") + "&a=rate&ajax=1", {"rating": $(this).nextAll(".star").andSelf().size()}, function(data) {
			rate_file.draw(element, data.rating);
			element.append("<span>" + data.message + "</span>");
		}, "json");
	},
	// draw rating stars
	draw: function(element, rating) {
		element.empty();

		var difference, i, star;
		for (i = 5; i >= 1; i--) {
			star = $.createElement("span").addClass("star").attr("title", rating + " / 5")
						.appendTo(element);

			if (i <= rating) {
				star.addClass("star_full");
			} else {
				difference = i - rating;
				if (difference <= 0.25) {
					star.addClass("star_full");
				} else if (difference <= 0.75) {
					star.addClass("star_half");
				} else {
					star.addClass("star_empty");
				}
			}
		}
	},
	// initiate stars
	init: function(element, file_id, rating, active) {
		if (typeof(element) == "string") {
			element = $("#"+ element);
		}

		element.data("file_id", file_id);
		rate_file.draw(element, rating);

		if (active != undefined && (active == 1 || active == true)) {
			element.children(".star").css("cursor", "pointer")
				.mouseover(rate_file.hover).mouseout(rate_file.clear)
				.click(rate_file.submit);
		}
	}
};

// files in full screen
var full_screen = {
	real_width: 0,
	real_height: 0,

	file: null,
	overlay: null,
	button: null,

	iframes: null, // we need to hide iframes because of Chrome bug

	// open full screen
	open: function() {
		full_screen.file.parent().css("height", full_screen.file.parent().height() + "px");

		full_screen.iframes = $("iframe:visible").hide();

		var position = full_screen.file.position();

		// start position
		full_screen.file.css({position: "absolute", "top": position.top + "px", "left": position.left + "px"});

		var from_top = $(window).scrollTop();
		var offset = full_screen.file.offset();
		var window_width = $(window).width();
		var window_height = $(window).height();

		// new width
		var new_width = window_width - 30;
		var change = new_width / full_screen.real_width;
		var new_height = full_screen.real_height * change;

		// new height
		if (new_height > window_height) {
			new_height = window_height - 30;
			change = new_height / full_screen.real_height;
			new_width = full_screen.real_width * change;
		}

		// stretch
		full_screen.file.animate({top: ((position.top - offset.top) + (window_height - new_height) / 2 + from_top)
			, left: ((position.left - offset.left) + (window_width - new_width) / 2)
			, width: new_width, height: new_height}
			, 1000);

		// close event
		$(document).one("click", full_screen.close);

		// stop event propagation
		full_screen.file.click(function(event) {
			event.stopPropagation();
		});

		// overlay
		if (full_screen.overlay == null) {
			var document_height = $(document).height();
			full_screen.overlay = $.createElement("div").attr("id", "resize_overlay")
				.width(window_width).height((document_height > window_height) ? document_height : window_height)
				.css({"top": position.top - offset.top, "left": position.left - offset.left})
					.insertBefore(full_screen.file);
		} else {
			full_screen.overlay.show();
		}
	},
	// close
	close: function() {
		full_screen.file.stop();
		full_screen.overlay.hide();
		full_screen.file.css("position", "static").width(full_screen.real_width)
			.height(full_screen.real_height);
		full_screen.iframes.show();
	},
	// initiate
	init: function() {
		full_screen.file = $("#resize_file");
		if (full_screen.file.size() == 0) {
			return;
		}

		// original width and height
		full_screen.real_width = this.file.width();
		full_screen.real_height = this.file.height();

		full_screen.button = $("#full_screen").show().click(function() {
        	full_screen.open();
        	return false;
		});
	}
};

// submit tell a friend form to server
function submit_tell_friend(form, file_id) {
	var submit = form.find("input:submit");
	loader.insert(submit);
	function response_function(response) {
		loader.remove(submit);
		error.insert(response.message, form, {hide: 3, error: response.error});
		if (!response.error) {
			form.find("input:text").val("");
			image_verification.attach("tell_image_verification"); // reload verification image
		}
	}
	$.post(siteurl + "file.php?a=tell_friend&f=" + file_id + "&ajax=1", form.serializeArray(), response_function, "json");
}

// submit report broken form to server
function submit_report_broken(form, file_id) {
	var submit = form.find("input:submit");
	loader.insert(submit);
	function response_function(response) {
		loader.remove(submit);
		error.insert(response.message, form, {error: response.error});
		if (!response.error) {
			form.delay(250).slideUp();
		}
	}
	$.post(siteurl + "file.php?a=report_broken&f=" + file_id + "&ajax=1", form.serializeArray(), response_function, "json");
}

// preloader ad on file page
var preloader = {
	time: 10,

	ad: null,
	file: null,
	loader: null,

	// hide ad
	hide: function(stop) {
		if (stop == true) {
			preloader.loader.children("div").stop();
		}
		preloader.ad.slideUp();
		preloader.file.slideDown();

		// show full screen button
		if (full_screen.button != null) {
			full_screen.button.show();
		}
	},
	// initiate loader
	init: function(preloader_time) {
		// intergi ad, so do nothing
		if ($("#intergi_wrapper_player").size() > 0) {
			$("#file_box").css("display", "none");
			return;
		}
	
		preloader.time = preloader_time;

		preloader.ad = $("#file_ad_box");
		if (preloader.ad.size() == 0) {
			return;
		}
		preloader.loader = $("#ad_loader").show();
		preloader.file = $("#file_box").hide();

		// hide full screen button (creates problems when clicked during ad)
		if (full_screen.button != null) {
			full_screen.button.hide();
		}

		$("#no_wait").show().children("a").click(function(e) {
			e.preventDefault();
			preloader.hide(true);
		});

		preloader.loader.children("div").animate({width: "100%"}
			, preloader.time * 1000
			, "linear"
			, preloader.hide);
	}
};

// manage scores
var scores = {

	file_id: 0,

	div_scoreboard: null,
	ul_cup: null,
	cup_menu: null,

	init: function(file_id) {
		scores.file_id = file_id;
		scores.div_scoreboard = $("#scoreboard");
		if (scores.div_scoreboard.size() == 0) {
			return;
		}

		scores.div_scoreboard.delegate("#all_scores", "click", function(e) {
			e.preventDefault();
			var button = $(this);
			loader.insert(button);
			button.remove();
			scores.load(1);
		});

		scores.init_cups();
	},

	init_cups: function() {
		scores.ul_cup = $("#cup_tabs");
		if (scores.ul_cup.size() == 0) {
			return;
		}

		// tabs
		scores.cup_menu = new tab_menu("cup_tabs");
		var cups_number = scores.ul_cup.children("li").size();
		for (var i = 0; i < cups_number; i++) {
			scores.cup_menu.add_action(i, scores.load_cup);
		}
		scores.cup_menu.init();
	},

	load: function(page) {
		$.getJSON(siteurl +"scores.php?ajax=1&id="+ scores.file_id +"&p="+ page, function(data) {
			scores.div_scoreboard.empty();
			for (var i in data.scores) {
				data.scores[i].me = data.scores[i].me ? ' me' : '';
				$.tmpl(template.score_line, data.scores[i]
						, scores.div_scoreboard);
			}

			if (data.previous <= 0 && data.next <= 0) {
				return;
			}

			var navigation = $.createElement("div").addClass("arrow_nav")
								.appendTo(scores.div_scoreboard);
			if (data.previous > 0) {
				$.createElement("a").attr("href", "").addClass("previous").html("&lt; "+ lang.previous)
					.click(data.previous, scores.navigation)
					.appendTo(navigation);
			}
			if (data.next > 0) {
				$.createElement("a").attr("href", "").addClass("next").html(lang.next +" &gt;")
					.click(data.next, scores.navigation)
					.appendTo(navigation);
			}
		});
	},

	navigation: function(e) {
		e.preventDefault();
		$(this).parent().children("a").unbind();
		loader.replace($(this).parent());
		if (e.data.tab != undefined) {
			scores.load_cup(e.data.tab, e.data.page);
		} else {
			scores.load(e.data);
		}
	},

	mochi: function(params) {
		if (scores.div_scoreboard == null) {
			return;
		}

		setTimeout(function() {
			// load main scoreboard
			scores.load_scoreboard();

			// load cups
			if (scores.cup_menu != null) {
				scores.cup_menu.get_tab(0).click();
			}
		}, 1000);
	},

	load_scoreboard: function() {
		loader.replace(scores.div_scoreboard);
		scores.div_scoreboard.load(siteurl +"scores.php?ajax=1&id="+ scores.file_id +"&a=scoreboard");
	},

	load_cup: function(tab_id, page) {
		var div_content = scores.cup_menu.get_content(tab_id);
		var cup_id = field_number(div_content.attr("id"));
		if (page == undefined) {
			page = 1;
			loader.replace(div_content);
		}

		$.getJSON(siteurl +"scores.php?a=cup&ajax=1&file_id="+ scores.file_id +"&cup_id="+ cup_id +"&p="+ page, function(data) {
			if (data.error) {
				div_content.html(data.message);
			}
			div_content.empty();

			for (var i in data.scores) {
				data.scores[i].me = (data.scores[i].me ? ' me': '');
			}

			$.tmpl(template.cup_score_line, data.scores, div_content);

			var navigation = $.createElement("div").addClass("arrow_nav").css("text-align", "center")
								.appendTo(div_content);
			navigation.append('<a href="'+ siteurl +'cup.php?id='+ cup_id +'" class="button">'+ lang.view_cup +'</a>');

			if (data.previous > 0) {
				$.createElement("a").attr("href", "").addClass("previous").html("&lt; "+ lang.previous)
					.click({page: data.previous, tab: tab_id}, scores.navigation)
					.appendTo(navigation);
			}
			if (data.next > 0) {
				$.createElement("a").attr("href", "").addClass("next").html(lang.next +" &gt;")
					.click({page: data.next, tab: tab_id}, scores.navigation)
					.appendTo(navigation);
			}
		});
	}

};

// init file page
function init_file_info(file_id, rating, rating_active, preloader_time) {
	$("#favorite").click(function(e) {
		e.preventDefault();
		var button = $(this);
		loader.insert(button);
		$.getJSON(siteurl + "file.php?a=make_favorite&f=" + file_id + "&ajax=1", function(response) {
			loader.remove(button);
			if (response.error) {
				alert(response.message);
				return;
			}
			button.html(response.text);
		});
	});

	rate_file.init($("#file_rating"), file_id, rating, rating_active);

	full_screen.init();

	$("#tell_friend_form").submit(function(e) {
		e.preventDefault();
		submit_tell_friend($(this), file_id);
	});
	$("#report_broken_form").submit(function(e) {
		e.preventDefault();
		submit_report_broken($(this), file_id);
	});

	// tabs
	var menu = new tab_menu("file_tabs");
	menu.add_action(2, function() {
		image_verification.attach("tell_image_verification");
	});
	menu.init();

	preloader.init(preloader_time);

	scores.init(file_id);
	
	$("#facebook_button").click(function(e) {
		e.preventDefault();
		menu.get_tab(2).click();
		$(document).scrollTop(menu.get_tab(2).offset().top);
	});
}

// init file frame
function init_frame() {
	$("#file_frame").height($(window).height() - $("#file_frame_info").height());
}

// file comments
var comments = {

	file_id: 0,
	max_comments: 10,
	page: 1,
	data: {},
	last_update: 0,
	update_timer: null,
	divComments: null,

	init: function(file_id, max_comments) {
		comments.file_id = file_id;
		comments.max_comments = max_comments;
		comments.divComments = $("#comments");

		comments.draw(comments.data.comments, comments.data.previous, comments.data.next, comments.data.time);
		comments.data = null;

		$("#comment_form").submit(function(e) {
			e.preventDefault();
			comments.submit($(this));
		});
		comments.divComments.delegate(".report", "click", function(e) {
			e.preventDefault();
			comments.report($(this));
		}).delegate("a.next, a.previous", "click", function(e) {
			e.preventDefault();
			comments.stop_timer();
			comments.divComments.children(".arrow_nav").remove();
			loader.appendTo(comments.divComments);
			comments.last_update = 0;
			comments.load(field_number($(this).attr("id")));
		});

		var comment_verification = $("#comment_verification_field");
		if (comment_verification.size() > 0) {
			$("#comment").focusin(function() {
				if (comment_verification.is(":hidden")) {
					comment_verification.show();
					image_verification.attach("comment_verification_field");
				}
			});
		}
	},

	draw: function(comm, previous, next, update_time) {
		if (previous == 0) {
			comments.update_timer = setTimeout(function() {
				comments.load(1);
			}, 60000);
		}

		if (comm.length == 0) {
			return;
		}

		comments.divComments.children(".arrow_nav, .loader").remove();

		if (comments.last_update == 0 || comm.length == comments.max_comments) {
			// new page
			comments.divComments.empty();

			for (var i in comm) {
				comm[i].lang_report = lang.report;
				comm[i].siteurl = siteurl;
				$.tmpl(template.comment, comm[i]
					, comments.divComments);

				// spam comment
				if (comm[i].spam) {
					comments.spam_comment($("#comment_"+ comm[i].id));
				}
			}
		} else {
			// append comments
			var live_comments = comments.divComments.children(".comment");
			var remove_comments = live_comments.size() + comm.length - comments.max_comments;
			if (remove_comments > 0) {
				var j = live_comments.size() - remove_comments;
				for (var i = live_comments.size() - 1; i >= j; i--) {
					live_comments.eq(i).remove();
				}
			}

			live_comments = comments.divComments.children(".comment");
			comm[0].lang_report = lang.report;
			comm[0].siteurl = siteurl;
			var first = $.tmpl(template.comment, comm[0]);
			if (live_comments.size() == 0) {
				comments.divComments.append(first);
			} else {
				first.insertBefore(live_comments.eq(0));
			}
			for (var i = comm.length; i > 1; i--) {
				comm[i].lang_report = lang.report;
				comm[i].siteurl = siteurl;
				$.tmpl(template.comment, comm[0])
					.insertAfter(first);
			}

			if (remove_comments > 0) {
				next = previous + 2;
			}
		}

		comments.last_update = update_time;

		if (previous > 0 || next > 0) {
			var pagination = $.createElement("div").addClass("arrow_nav")
								.appendTo(comments.divComments);
			if (previous > 0) {
				$.createElement("a").attr({id: "cpage_"+ previous, href: ""}).addClass("previous").html("&lt; "+ lang.newer)
					.appendTo(pagination);
			}
			if (next > 0) {
				$.createElement("a").attr({id: "cpage_"+ next, href: ""}).addClass("next").html(lang.older +" &gt;")
					.appendTo(pagination);
			}
		}
	},

	report: function(button) {
		var comment = button.closest(".comment");
		comments.spam_comment(comment);
		button.hide();
		$.getJSON(siteurl + "file.php?a=report_comment&ajax=1&id=" + field_number(comment.attr("id")));
	},

	// hide/show spam comments
	spam_comment: function(comment) {
		comment.addClass("spam");

		var text = comment.find(".text:first");
		text.hide();

		//comment.find(".report:first").hide();
		comment.mouseenter(function() {
			if (text.is(":hidden")) {
				text.slideDown();
			}
		}).mouseleave(function() {
			if (text.is(":visible")) {
				text.slideUp();
			}
		});
	},

	load: function(page) {
		$.getJSON(siteurl + "file.php?a=comments&ajax=1&f=" + comments.file_id + "&p=" + page +"&last_update="+ comments.last_update, function(data) {
			if (data.error) {
				alert(data.message);
				return;
			}
			comments.draw(data.comments, data.previous, data.next, data.time);
		});
	},

	submit: function(form) {
		comments.stop_timer();
		var submit = form.find("input[type='submit']");
		loader.insert(submit);
		$.post(siteurl + "file.php?a=submit_comment&ajax=1&f=" + comments.file_id +"&last_update="+ comments.last_update, form.serialize(), function(data) {
			loader.remove(submit);
			error.insert(data.message, form, {error: data.error != undefined && data.error, hide: 2});
			if (!data.error) {
				comments.draw(data.comments, data.previous, data.next, data.time);
				form.find("textarea,input[type='text']").val("");
			}
		}, "json");
	},

	stop_timer: function() {
		try {
			clearTimeout(comments.update_timer);
		} catch(e) {}
	}

};





// change score comment
var score_comment = {
	score_id: 0,
	comment: null,
	button: null,
	// initiate comment form
	change: function(button) {
		this.comment = button.closest("p");
		this.score_id = field_number(this.comment.attr("id"));
		this.button = button.detach();
		this.comment.empty();

		// new comment form
		var form = $.createElement("form");

		var input = $.createElement("input").attr("type", "text").width("100%").css("margin", 0)
			.appendTo(form);
		$.createElement("input").attr("type", "submit").val(lang.submit)
			.appendTo(form);

		form.submit(function() {
			score_comment.submit(input.val());
			return false;
		}).appendTo(this.comment);

		input.focus();
	},
	// submit new comment to server
	submit: function(value) {
		loader.replace(this.comment);
		function response_function(response) {
			if (response.error) {
				alert(response.message); return;
			}
			score_comment.comment.html(response.comment + " ");
			score_comment.comment.append(score_comment.button);
		}
		$.post(siteurl + "scores.php?a=edit_comment&ajax=1&id=" + score_comment.score_id, {"comment": value}, response_function, "json");
	}
};

// bb code management object
var bb_code = {
	codes: [["text_bold.png","b"],["text_italic.png","i"],["text_underline.png","u"],["text_strikethrough.png","s"],["text_center.png","center"],["text_right.png","right"],["text_quote.png","quote"],["text_url.png","url"],["text_image.png","img"]],
	emoticons: [["happy.gif", ":)"],["sad.gif", ":("],["wink.gif",";)"],["@.gif",":@"],["cool.gif",":8"],["wave.gif",":wave:"],["think.gif",":think:"],["clap.gif",":clap:"]],
	open: {},
	insert_emoticon: function(code, textarea) {
		code = " " + code + " ";
		textarea.focus();

		if (document.selection) {
			document.selection.createRange().text = code;
		} else if (textarea.selectionStart || textarea.selectionStart == 0) {
			var selection_start = textarea.selectionStart;
			var selection_end = textarea.selectionEnd;
			var scroll_top = textarea.scrollTop;

			textarea.value = textarea.value.substring(0, selection_start) + code + textarea.value.substring(selection_end, textarea.value.length);

			textarea.selectionStart = selection_start + code.length;
			textarea.selectionEnd = selection_start + code.length;
			textarea.scrollTop = scroll_top;
		} else {
			textarea.value += code;
		}
	},
	get_tag: function(code) {
		if (bb_code.open[code] == undefined || bb_code.open[code] == false) {
			bb_code.open[code] = true;
			return "[" + code + "]";
		} else {
			bb_code.open[code] = false;
			return "[/" + code + "]";
		}
	},
	insert_code: function(code, textarea) {
		textarea.focus();

		// positions and selected text
		if (document.selection) {
			var selected = document.selection.createRange().text;
			var type = "ie";
		} else if (textarea.selectionStart || textarea.selectionStart == 0) {
			var selection_start = textarea.selectionStart;
			var selection_end = textarea.selectionEnd;
			var scroll_top = textarea.scrollTop;

			var before = textarea.value.substring(0, selection_start);
			var after = textarea.value.substring(selection_end, textarea.value.length);
			var selected = textarea.value.substring(selection_start, selection_end);

			var type = "other";
		}

		if (code == "url") {
			if (type == "ie") {
				if (selected.length > 0) {
					if (selected.match(/^https?:\/\//i)) {
						document.selection.createRange().text = "[url=" + selected + "]" + selected + "[/url]";
					} else {
						document.selection.createRange().text = "[url=http://]" + selected + "[/url]";
					}
				} else {
					document.selection.createRange().text = "[url=http://]text[/url]";
				}
			} else if (type == "other") {
				if (selected.length > 0) {
					if (selected.match(/^https?:\/\//i)) {
						textarea.value = before + "[url=" + selected + "]" + selected + "[/url]" + after;
						selection_start += 6 + selected.length;
						selection_end = selection_start + selected.length;
					} else {
						textarea.value = before + "[url=http://]" + selected + "[/url]" + after;
						selection_start += 5;
						selection_end = selection_start + 7;
					}
				} else {
					textarea.value = before + "[url=http://]text[/url]" + after;
					selection_start += 5;
					selection_end = selection_start + 7;
				}
			} else {
				textarea.value += "[url=http://]text[/url]";
			}
		} else if (code == "img") {
			if (type == "ie") {
				document.selection.createRange().text = (selected.length > 0) ? "[img]" + selected + "[/img]" : "[img]http://[/img]";
			} else if (type == "other") {
				if (selected.length > 0) {
					textarea.value = before + "[img]" + selected + "[/img]" + after;
					selection_start += 5;
					selection_end = selection_start + selected.length;
				} else {
					textarea.value = before + "[img]http://[/img]" + after;
					selection_start += 5;
					selection_end += 12;
				}
			} else {
				textarea.value += "[img]http://[/img]";
			}
		} else {
			if (type == "ie") {
				if (selected.length > 0) {
					document.selection.createRange().text = "[" + code + "]" + selected + "[/" + code + "]";
				} else {
					document.selection.createRange().text = bb_code.get_tag(code);
				}
				textarea.focus();
			} else if (type == "other") {
				if (selected.length > 0) {
					textarea.value = before + "[" + code + "]" + selected + "[/" + code + "]" + after;
					selection_start += code.length + 2;
					selection_end += code.length + 2;
				} else {
					code = bb_code.get_tag(code);
					textarea.value = before + code + after;
					selection_start += code.length;
					selection_end = selection_start;
				}
			} else {
				textarea.value += bb_code.get_tag(code);
			}
		}

		// get correct selection
		if (type == "other") {
			textarea.selectionStart = selection_start;
			textarea.selectionEnd = selection_end;
			textarea.scrollTop = scroll_top;
		}
	},
	attach_emoticons: function(buttons, textarea) {
		buttons = $("#" + buttons);
		textarea = $("#" + textarea).get(0);

		var p = $.createElement("p");
		for (i in bb_code.emoticons) {
			$.createElement("img").attr("src", siteurl + "images/" + bb_code.emoticons[i][0]).attr("alt", bb_code.emoticons[i][1]).attr("title", bb_code.emoticons[i][1])
				.click(function() { bb_code.insert_emoticon($(this).attr("alt"), textarea); }).addClass("bb_emoticon").appendTo(p);
		}
		p.appendTo(buttons);
	},
	attach_codes: function(buttons, textarea) {
		buttons = $("#" + buttons);
		textarea = $("#" + textarea).get(0);

		var p = $.createElement("p");
		for (i in bb_code.codes) {
			$.createElement("img").attr("src", siteurl + "images/" + bb_code.codes[i][0]).attr("alt", bb_code.codes[i][1]).attr("title", bb_code.codes[i][1])
				.click(function() { bb_code.insert_code($(this).attr("alt"), textarea); }).addClass("bb_code").appendTo(p);
		}
		p.appendTo(buttons);
	},
	attach: function(buttons, textarea) {
		bb_code.attach_emoticons(buttons, textarea);
		bb_code.attach_codes(buttons, textarea);
	}
};

// iframe for adding files to other websites
function init_iframe(ad_time) {
	var ad = $("#iframe_ad");
	if (ad.size() == 0) {
		return;
	}

	var loader = $("#ad_loader");
	var file = $("#iframe_file").hide();

	$("#no_wait").children("a").click(function(e) {
		e.preventDefault();
		ad.hide();
		file.show();
	});

	loader.children("div").animate({width: "100%"}
		, ad_time * 1000
		, "linear"
		, function() {
			ad.hide();
			file.show();
		});
}

function init_index() {
	var divNewGames = $("#new_games");
	divNewGames.delegate(".pagination a", "click", function(e) {
		e.preventDefault();
		var button = $(this);
		var page = field_number(button.attr("id"));
		loader.replace(button.closest(".pagination"));
		divNewGames.load("index.php?ajax=1&p="+ page);
	});
}
