var _is_debug = false,	// debug switch
		
		_redirect = function(url, new_window) {
			/**
			 * Depending on how this is used, new_window might lead to popup block
			 * trigger, make sure you test before using it.
			 */
			if (typeof url == 'undefined')
				url = document.location.href;
			
			if (typeof new_window == 'undefined')
				new_window = false;
			
			if (new_window === true) {
				window.open(url);
			} else {
				if (document.location.href == url && url.indexOf("#") != -1) {
					/**
					 * We're trying to reload a hash page, document.location.href will
					 * not work here, we need to refresh the page
					 *
					 * http://www.quackit.com/javascript/javascript_refresh_page.cfm
					 */
					location.reload(true);
				} else {
					document.location.href = url;
				}
			}
			
			return false;
		},
		
		/**
		 * Alerts Object
		 * Manage `My Alerts`
		 * Related to #8159
		 */
		alerts = {
			del: function(type) {
				type = parseInt(type);
				
				if (confirm(type < 0 ? "Are you sure you want to delete all the existing alerts?" : "Are you sure you want to delete all the existing alerts for this type?"))
					_redirect("/myalerts.php?action=delete&type=" + type);
				
				return false;
			}
		},
		
		/**
		 * User Gallery object
		 * Loads gallery listings inside a folder
		 * This object is also used for the favorites
		 * Related to #7972
		 *
		 */
		ugallery = {
			lib: "/ajax_usergallery_folder.php",
			showAll: function(){
				var $this = this;
				$.each($("#tgl_all").val().split("|"), function(k, v) {
					if (v != "")
						if (!$("#ug_" + v).is(":visible"))
							$this.toggle(v);
				});
				$("#ug_showAll").hide();
				$("#ug_hideAll").show();
				
				return false;
			},
			
			hideAll: function(){
				var $this = this;
				$.each($("#tgl_all").val().split("|"), function(k, v) {
					if (v != "")
						if ($("#ug_" + v).is(":visible"))
							$this.toggle(v);
				});
				
				$("#ug_showAll").show();
				$("#ug_hideAll").hide();
				
				return false;
			},
			
			toggle: function(id) {
				if ($("#ug_" + id).html() == "") {
					$("#ug_" + id).html("<img src='/img/ajax-loader.gif'> Loading...");
					
					var $this = this;
					
					// load gallery listing via ajax
					$.ajax({
						url: $this.lib,
						type:"GET",
						data:"id=" + id + "&userid=" + $("input[id=userid_input]").val(),
						dataType:'html',
						cache:true,
						async:true,
						timeout:12000000,
						scriptCharset:"UTF-8",
						success:function(r, s) { $("#ug_" + id).html(r == "" ? "<i>Empty</i>" : r); }
					});
				}
				
				$("#ug_" + id).slideToggle("fast", function(){
					if ($(this).is(":visible")) { // visible
						$("#img_" + id).attr("src", "/img/arrow_down.gif");
					} else { // hidden
						$("#img_" + id).attr("src", "/img/arrow_left.gif");
					}
				});
			
				return false;
			}
		}
		
		/**
		 * Message object
		 * Used to load recently received messages by the user (at header)
		 * 
		 */
		msg = {
			loaded: false,
			
			/**
			 * Used on the hovering of newest messages at header, this function will
			 * fetch the latest message snippets and put them on the header box.
			 *
			 * Related to #7934
			 */
			load: function() {
				if (this.loaded)
					return;
					
				$.ajax({
					url: "/ajax_last_messages.php",
					type:"GET",
					dataType:'html',
					cache:true,
					async:true,
					timeout:12000000,
					scriptCharset:"UTF-8",
					success:function(r, s) { $(".msgCont").html(r); }
				});
				
				this.loaded = true;
			}
		},
		
		/**
		 * Captcha managing object
		 * 
		 * @note `captcha` with A, don't work somehow, some other lib must
		 *       be conflicting with this name.
		 */
		captch = {
			i: 0,
			
			retry: function() {
				alert("Confirmation code is wrong, please try again.");
				this.refresh();
			},
			
			refresh: function(){
				var rand = Math.random();
				
				$("img[id=captcha]").each(function(){
					$(this).attr("src", "/captcha.php?" + rand);
				});
				
				this.i++;
				return false;
			},
			
			init:function(){
				if (this.i == 0)
					this.refresh();
			}
		},
		
		/**
		 * Region object
		 * Loads regions based on country selection
		 * Ref to #7947
		 *
		 * - Rodrigo
		 */
		region = {
			load: function(countryid, sel) {
				if (typeof sel == 'undefined')
					sel = "";
				
				if (countryid == "" || countryid == 0) {
					$("#formregion").html("<option value=''>Select a country first</option>");
				} else {
					$.ajax({
						url: "/ajax_region.php",
						type:"POST",
						data: "countryid=" + countryid + "&sel=" + sel,
						dataType:'html',
						cache:true,
						async:true,
						timeout:12000000,
						scriptCharset:"UTF-8",
						beforeSend:function(){ $("#formregion").html("<option value=''>Loading...</option>"); },
						success:function(r, s) {
							switch (parseInt(r)) {
								case 500:
									alert("Invalid post data");
									break;
								
								case 501:
									alert("Missing inputs");
									break;
								
								case 502:
									alert("Invalid input");
									break;
								
								default:
									$("#formregion").html(r);
							}
						}
					});
				}
			},
			
			init: function() {
				var $this = this;
				
				if ($("#formcountry").length > 0) {
					$("#formcountry").change(function(){ $this.load($(this).val()); });
					
					// load regions from this country
					$this.load(
						$("#formcountry").val(),
						$("#formregion_hidden").length > 0 && $("#formregion_hidden").val() != "" ? $("#formregion_hidden").val() : ""
					);
				}
			}
		},
		
		/**
		 * Comment object
		 * This controls all ajax features for commenting pictures.
		 * Ref to #7837
		 *
		 * - Rodrigo
		 */
		comment = {
			id: null,
			
			replyCancel: function() {
				$(this.id + "_cid").val("");
				$(this.id + "_content").val("");
				$(this.id + "_reply").hide();
				$(this.id + "_first").hide();
				$(this.id + "_many").show();
				
				return false;
			},
			
			reply: function(id, who) {
				if (typeof id == 'undefined' || id == "" || parseInt(id) <= 0)
					return false;
				
				$(this.id + "_many").hide();
				$(this.id + "_first").hide();
				$(this.id + "_reply").show();
				$(this.id + "_reply_who").html(who);
				$(this.id + "_cid").val(id);
				$(this.id + "_content").click().focus();
				$.scrollTo($(this.id + "_content"), {offset: -50});
				
				return false;
			},
			
			load: function(id) { // load comments via ajax
				var $this = this;
				
				$.ajax({
					url: "/ajax_comments.php",
					type:"POST",
					data: "id=" + id,
					dataType:'html',
					cache:true,
					async:true,
					timeout:12000000,
					scriptCharset:"UTF-8",
					success:function(r, s) {
						$("#cntComments").html(r);
						$($this.id + "_cid").val("");
						
						if (r != "") {
							$($this.id + "_many").show();
							$($this.id + "_first").hide();
							$($this.id + "_reply").hide();
						} else {
							$($this.id + "_reply").hide();
							$($this.id + "_many").hide();
							$($this.id + "_first").show();
						}
					}
				});
			},

			loadVideo: function(id) { // load comments via ajax
				var $this = this;
				
				$.ajax({
					url: "/ajax_comments.php",
					type:"POST",
					data: "vid=" + id,
					dataType:'html',
					cache:true,
					async:true,
					timeout:12000000,
					scriptCharset:"UTF-8",
					success:function(r, s) {
						$("#cntComments").html(r);
						$($this.id + "_cid").val("");
						
						if (r != "") {
							$($this.id + "_many").show();
							$($this.id + "_first").hide();
							$($this.id + "_reply").hide();
						} else {
							$($this.id + "_reply").hide();
							$($this.id + "_many").hide();
							$($this.id + "_first").show();
						}
					}
				});
			},

			send: function(){
				if ($(this.id).valid()) {
					var $this = this;
					
					$.ajax({
						url: "/ajax_comment.php",
						data: "comment=" + $("#comments_content").val() + "&comments_captcha=" + $("#comments_captcha").val() + ($("input[id=imageid_input]").length > 0 ? "&imgid=" + $("input[id=imageid_input]").val() : "") + ($("input[id=videoid_input]").length > 0 ? "&vid=" + $("input[id=videoid_input]").val() : "") + "&gid=" + $("input[id=galleryid_input]").val() + ($(this.id + "_cid").val() != "" ? "&cid=" + $(this.id + "_cid").val() : ""),
						type:"POST",
						dataType:"html",
						async:true,
						timeout:12000000,
						scriptCharset:"UTF-8",
						beforeSend: function() { $($this.id).find("#cf").hide();$($this.id).find("#cf_loading").show(); },
						complete: function() { $($this.id).find("#cf").show();$($this.id).find("#cf_loading").hide(); },
						success:function(r, s) {
							switch (parseInt(r)) {
								case 500: // catpcha error
									captch.retry();
									break;
								
								case 501:
									alert("The owner of this gallery has blocked you, can't add comment.");
									break;
								
								case 502:
									alert("Invalid inputs.");
									break;
								
								case 503:
									alert("Missing inputs.");
									break;
								
								case 504:
									alert("You're not logged in, redirecting to login page...");
									_redirect("/login.php?backurl=" + document.location.href.replace(/#/g,"@@@"));
									break;
								
								case 200: // all good, close/reset the box
									$($this.id)[0].reset();
									
									if ($("input[id=videoid_input]").length > 0)
										$this.loadVideo($("input[id=videoid_input]").val());
									else
										$this.load($("input[id=imageid_input]").val());
									break;
							}
						}
					});
				}
				
				return false;
			},
			
			init: function(id) {
				this.id = id;
				
				// apply validator
				$(this.id).validate({
					rules: {
						"comments_content": "required",
						"comments_captcha": {
							"required": true,
							"minlength": 4
						}
					},
					messages: {
						"comments_content": "",
						"comments_captcha": ""
					}
				});
				
				$(this.id + "_content").click(function(){
					$(".cntCommentControls").show();
					captch.init();
				});
				
				$(this.id + ($("#cntComments").html() != "" ? "_many" : "_first")).show();
			}
		},
		
		/**
		 * Share content object
		 * This will use a overlay to share the current picture or gallery
		 * Ref to #7837
		 *
		 * - Rodrigo
		 */
		share = {
			api: null,
			id: null,
			
			send: function() {
				if ($(this.id + "_form").valid()) {
					var $this = this;
					
					$.ajax({
						url: "/ajax_share.php",
						data: "who=" + $("#share_who").val() + "&share_eml=" + $("#share_eml").val() + "&share_usr=" + $("#share_usr").val() + "&share_captcha=" + $("#share_captcha").val() + ($("input[id=imageid_input]").length > 0 ? "&imgid=" + $("input[id=imageid_input]").val() : "") + "&gid=" + $("input[id=galleryid_input]").val(),
						type:"POST",
						dataType:"html",
						async:true,
						timeout:12000000,
						scriptCharset:"UTF-8",
						beforeSend: function() { $($this.id).find("#cf").hide();$($this.id).find("#cf_loading").show(); },
						complete: function() { $($this.id).find("#cf").show();$($this.id).find("#cf_loading").hide(); },
						success:function(r, s) {
							switch (parseInt(r)) {
								case 500: // catpcha error
									captch.retry();
									break;
								
								case 501: // invalid input
									alert("None of the friends you added are valid usernames or emails.");
									break;
								
								case 502: // partially invalid
									alert("One or more of your recommended friends are invalid.");
									break;
								
								case 200: // all good, close/reset the box
									$($this.id + "_form")[0].reset();
									$this.close();
									break;
							}
						}
					});
				}
				
				return false;
			},
			
			show: function() {
				if (this.api == null) // avoids javascript errors when the document is not ready
					this.init("#share");
				
				captch.init();
				this.api.load();
				return false;
			},
			
			close: function() {
				this.api.close();
				return false;
			},
			
			init: function(id) {
				if (this.api != null)
					return;
					
				$(id).overlay({
					mask: {
						color: "#fff",
						loadSpeed: 500,
						opacity: 0.7
					},
					
					load: false
				});
				
				this.api = $(id).data("overlay");
				this.id = id;
				
				// apply validator
				$(this.id + "_form").validate({
					rules: {
						"share_who": "required",
						"share_usr": "required",
						"share_eml": {
							"required": true,
							"email": true
						},
						"share_captcha": {
							"required": true,
							"minlength": 4
						}
					},
					messages: {
						"share_who": "",
						"share_usr": "",
						"share_eml": "",
						"share_captcha": ""
					}
				});
			}
		},
		
		/**
		 * Flagging content object
		 * This will use a overlay to flag the current picture or gallery
		 * Ref to #7837
		 *
		 * - Rodrigo
		 */
		flag = {
			api: null,
			id: null,
			
			send: function() {
				if ($(this.id + "_form").valid()) {
					var $this = this;
					
					$.ajax({
						url: "/ajax_flag.php",
						data: ($("input[id=imageid_input]").length > 0 ? "abuse=1&imgid=" + $("input[id=imageid_input]").val() : "abuse=2") + "&gid=" + $("input[id=galleryid_input]").val() + "&flag_usr=" + $("#flag_usr").val() + "&flag_eml=" + $("#flag_eml").val() + "&flag_reason=" + $("#flag_reason").val() + "&flag_captcha=" + $("#flag_captcha").val(),
						type:"POST",
						dataType:"html",
						async:true,
						timeout:12000000,
						scriptCharset:"UTF-8",
						beforeSend: function() { $($this.id).find("#cf").hide();$($this.id).find("#cf_loading").show(); },
						complete: function() { $($this.id).find("#cf").show();$($this.id).find("#cf_loading").hide(); },
						success:function(r, s) {
							if (r == "500") { // error return
								captch.retry();
							} else { // all good, close/reset the box
								$($this.id + "_form")[0].reset();
								$this.close();
							}
						}
					});
				}
				
				return false;
			},
			
			show: function() {
				if (this.api == null) // avoids javascript errors when the document is not ready
					this.init("#flag");
				
				captch.init();
				this.api.load();
				return false;
			},
			
			close: function() {
				this.api.close();
				return false;
			},
			
			init: function(id) {
				if (this.api != null)
					return;
					
				$(id).overlay({
					mask: {
						color: "#fff",
						loadSpeed: 500,
						opacity: 0.7
					},
					
					load: false
				});
				
				this.api = $(id).data("overlay");
				this.id = id;
				
				// apply validator
				$(this.id + "_form").validate({
					rules:{
						"flag_usr": "required",
						"flag_eml": {
							"required": true,
							"email": true
						},
						"flag_reason": "required",
						"flag_captcha": {
							"required": true,
							"minlength": 4
						}
					},
					
					messages:{
						"flag_usr":"",
						"flag_eml":"",
						"flag_reason":"",
						"flag_captcha":""
					}
				});
			}
		},
		
		/**
		 * Announces Object
		 * @requires jquery.cookie
		 *
		 * Related to #7794
		 *
		 * - Rodrigo
		 */
		announce = {
			close: function() {
				$(".announceBox").hide();
				
				$.ajax({
					url: "/ajax_announce.php",
					dataType:"html",
					async:true,
					timeout:12000000,
					scriptCharset:"UTF-8"
				});
				
				return false;
			}
		},
		
		/**
		 * Favorites object
		 *
		 * Manage all favorites related add to settings
		 *
		 * - Rodrigo
		 */
		favorites = {
			id: null,
			
			init: function(id){
				this.id = id;
				
				$("#" + id).change(function(){
					var $this = $(this),
							opts = "",
							fid = $(this).val();
					
					// collect select values
					$(this).find("option").each(function(){ opts += $(this).val() + "|"; });
					
					switch ($(this).val()) {
						case "__NEW_PICTURE__": // adds a new picture folder
							var name = prompt("What's the name of the new picture folder you want to create?");
							name = $.trim(name);
							
							if (name != "") {
								$.ajax({
									url: "/ajax_favorites.php",
									data: "action=0&name=" + name + "&imgid=" + $("input[id=imageid_input]").val() + "&gid=" + $("input[id=galleryid_input]").val(),
									type:"POST",
									dataType:"html",
									async:true,
									timeout:12000000,
									scriptCharset:"UTF-8",
									beforeSend: function() { $(".addTo_loading").show(); },
									complete: function() { $(".addTo_loading").hide(); },
									success:function(r, s) {
										switch (parseInt(r)) {
											case 500: // invalid name
												alert("Invalid name");
												$this.val(""); // don't update just set the value back to nothing
												break;
											
											case 501: //  not logged in
												alert("You're not logged in, redirecting to login page...");
												_redirect("/login.php?backurl=" + document.location.href.replace(/#/g,"@@@"));
												break;
											
											case 502: // folder already exists
												alert("This folder name already exists");
												$this.val("");
												break;
											
											default: // all good, this will return the drop down contents again
												$this.html(r);
												
												// now we find the different id
												$this.find("option").each(function(){
													if (opts.indexOf($(this).val()) == -1)
														fid = $(this).val();
												});
												
												favorites.updateSpan(fid);
												
												break;
										}
									}
								});
							} else {
								alert("Invalid name.");
							}
							break;
						
						case "__NEW_GALLERY__": // adds a new gallery folder
							var name = prompt("What's the name of the new gallery folder you want to create?")
							name = $.trim(name);
							
							if (name != "") {
								$.ajax({
									url: "/ajax_favorites.php",
									data: "action=1&name=" + name + "&imgid=" + $("input[id=imageid_input]").val() + "&gid=" + $("input[id=galleryid_input]").val(),
									type:"POST",
									dataType:"html",
									async:true,
									timeout:12000000,
									scriptCharset:"UTF-8",
									beforeSend: function() { $(".addTo_loading").show(); },
									complete: function() { $(".addTo_loading").hide(); },
									success:function(r, s) {
										switch (parseInt(r)) {
											case 500: // invalid name
												alert("Invalid name");
												$this.val(""); // don't update just set the value back to nothing
												break;
											
											case 501: //  not logged in
												alert("You're not logged in, redirecting to login page...");
												_redirect("/login.php?backurl=" + document.location.href.replace(/#/g,"@@@"));
												break;
											
											case 502: // folder already exists
												alert("This folder name already exists");
												$this.val("");
												break;
											
											default: // all good, this will return the drop down contents again
												$this.html(r);
												
												// now we find the different id
												$this.find("option").each(function(){
													if (opts.indexOf($(this).val()) == -1)
														fid = $(this).val();
												});
												
												favorites.updateSpan(fid);
												
												break;
										}
									}
								});
							} else {
								alert("Invalid name.");
							}
							break;
						
						case "":
							// do nothing, bitch slap!
							break;
						
						default: // add to an existing folder
							$.ajax({
								url: "/ajax_favorites.php",
								data: "action=2&name=" + $(this).val() + "&imgid=" + $("input[id=imageid_input]").val() + "&gid=" + $("input[id=galleryid_input]").val(),
								type:"POST",
								dataType:"html",
								async:true,
								timeout:12000000,
								scriptCharset:"UTF-8",
								beforeSend: function() { $(".addTo_loading").show(); },
								complete: function() { $(".addTo_loading").hide(); },
								success:function(r, s) {
									switch (parseInt(r)) {
										case 502:
											alert("This item already exists inside the folder you're trying to add.");
											break;
											
										default: // just update the box
											favorites.updateSpan(fid);
											break;
									}
									
									$this.val(""); // don't update just set the value back to nothing
								}
							});
							break;
					}
					
					$(this).val("");
				});
			},
			
			updateSpan: function(fid) {
				//_dbg($("#" + this.id).find("option[value=" + fid + "]").text());
				if (fid.indexOf("|") != -1)
					fid = fid.substr(fid.indexOf("|") + 1);
				
				$("." + this.id + "_result").html("<BR>Added to favorites, <a href='/favoritesmap.php?mid=" + fid + "' target='_blank'>view my favorites</a>.").show();
			}
		},
		
		/**
		 * Blocks a user without showing fireworks, but trigger an alert to warn.
		 * Similar to widget behaivor.
		 *
		 * Related to #8065
		 *
		 * - Rodrigo
		 */
		internalBlock = function(userid) {
			if (typeof userid == 'undefined')
				return;
			
			userid = parseInt(userid);
			
			if (userid <= 0)
				return;
			
			$.ajax({
				url: "/myblockedusers.php",
				type: "POST",
				data: "action=block&blockid=" + userid,
				dataType:"json",
				async:true,
				timeout:12000000,
				scriptCharset:"UTF-8",
				success:function (i, r) {
					alert("User has been blocked!");
				}
			});
			
			return false;
		},
		
		_dom_trackActiveElement = function(evt) {
			if (evt && evt.target)
				document.activeElement = evt.target == document ? null : evt.target;
		},
		
		_dom_trackActiveElementLost = function(evt) { 
			document.activeElement = null;
		},
		
		ScaleSize = function(maxW, maxH, currW, currH) {
			var ratio = currH / currW;
			
			if (currW > maxW) {
				currW = maxW;
				currH = currW * ratio;
			} else if (currH > maxH) {
				currH = maxH;
				currW = currH / ratio;
			}
			
			return {
				"width":Math.round(currW),
				"height":Math.round(currH)
			};
		},
		
		_dbg = function(x) { if (_is_debug && typeof console != 'undefined') { console.log(x); } };

$(document).ready(function(){
	if ($("#cntBanner").length > 0)
		$("#cntBanner").scrollFollow({
			speed: 0
		});
	
	if ($("#mbBanner").length > 0) {
		$("#mbBanner").scrollFollow({
			easing: "linear_mb",
			killSwitch: "mbBannerCloseLNK",
			onText: '<img src="/img/close.gif" height=16 width=16 border=0>',
			offText: ' ',
			speed: 1
		});
	}
	
	if ($("#lst_visitors").length > 0)
		$("#lst_visitors").click(function(){
			$("#cnt_lst_visitors").toggle();
			
			return false;
		});
	
	if ($("#flag_lnk").length > 0)
		flag.init("#flag");
	
	if ($("#share_lnk").length > 0)
		share.init("#share");
	
	if ($("#comments").length > 0)
		comment.init("#comments");
	
	if ($("#addTo").length > 0)
		favorites.init("addTo");
	
	// special handler for currently focused element - http://stackoverflow.com/questions/483741/how-to-determine-which-html-page-element-has-focus
	if (!document.activeElement) {
		document.addEventListener("focus",_dom_trackActiveElement,true);
		document.addEventListener("blur",_dom_trackActiveElementLost,true);
	}
	
	region.init(); // start region object
	
	$(".relHover, .msgHover").hover(function(){
		var p = $(this).attr("class").substr(0,3);
		$("." + p + "Cont").show();
		
		if (p == "msg")
			msg.load();
	}, function(){
		var p = $(this).attr("class").substr(0,3);
		$("." + p + "Cont").hide();
	});
	
	if ($("#alertSel").length > 0)
		$("#alertSel").change(function(){
			_redirect("/myalerts.php" + ($(this).val() != "" ? "?type=" + $(this).val() : ""));
		});
	
});

jQuery.extend( jQuery.easing, {
	linear_mb: function( p, n, firstNum, diff ) {
		if ($("#mbBanner").css("top") != "0px")
			$("#mbBannerClose").show();
		else
			$("#mbBannerClose").hide();
		
		return firstNum + diff * p;
	}
});

