// A little shortcus for the pretty messages
$.fn.addMessage = function(text, timeout) {
	if (timeout == undefined) {
		timeout = 2000;
	}
	var messages = this.find("span.message");
	var arrow = $("<span>").addClass("arrow");
	var message = $("<span>").addClass("message").html(text).prepend(arrow).click(function() { return false; });
	if (messages.size() > 0) {
		messages.remove();
	} else {
		message.hide().fadeIn("fast");
	}
	this.append(message.delay(timeout).fadeOut("fast", function() { $(this).remove(); }));
	return message;
};

// Serialize form data as an object
$.fn.serializeObject = function(filter) {
	var result = { };
	var dupes = { };
	var items = this.find(":input[name]");
	if (typeof filter == "string") {
		items = items.filter(filter);
	}
	
	items.each(function() {
		var name = this.name;
		if (name.substring(-2) == "[]") {
			if (dupes[name] == undefined)
				dupes[name] = 0;
			name = name.substring(0, -2) + "[" + dupes[name] + "]";
			dupes[name]++;
		}
		if ($(this).is(":checkbox")) {
			result[name] = this.checked? "yes" : "no";
		} else if (!$(this).is(":radio") || $(this).is(":checked")) {
			result[name] = $(this).val();
		}
	});
	return result;
}

// Get the list of scenes on this page
function get_item_keys(selector) {
	var list = [];
	$(selector).each(function() {
		var bit = this.href.split(".html").shift().split("/").pop().split("-").pop();
		list.push(parseInt(bit));
	});
	return list;
}

// Apply clickable timestamps to comments
function parseTimestamps(selector) {
	$("span.body", selector).each(function() {
		var text = $(this).html().replace(/[0-9]{1,2}:[0-9]{1,2}/g, function(match) {
			var parts = match.split(":");
			var time = parseInt(parts[0]) * 60 + parseInt(parts[1]);
			return '<a href="#' + time + '" class="timestamp">' + match + '</a>';
		});
		$(this).html(text);
	});
}

// Estimate user bandwidth
function getBandwidth(force) {
	var start = (new Date()).getTime();
	var image = new Image();
	image.src = "/images/bwcheck.png#" + start;
	image.onload = function() {
		var end = (new Date()).getTime();
		var diff = (end - start) / 1000;
		var bandwidth = (514033 / diff) / 1024;
		$.cookie("bandwidth_detected", Math.round(bandwidth), { path: "/" });
	};
}

//Setup image roll
function rollImages(thumb, start) {
	if (thumb.origimg == undefined) {
		thumb.origimg = $(thumb).css("background-image");
		thumb.images = { };
	}
	if (start == undefined || start > 10) {
		if (thumb.origimg.match(/promo_[0-9]+\.jpg$/)) {
			start = 2;
		} else {
			start = 1;
		}
	}
	if (thumb.images[start] == undefined) {
		rollNewImage(thumb, start);
	}
	if (start < 10 && thumb.images[start + 1] == undefined) {
		rollNewImage(thumb, start + 1);
	}
	var img = thumb.images[start];
	if (img.complete) {
		thumb.style.backgroundImage = 'url("' + img.src + '")';
		thumb.timerID = setTimeout (function() { rollImages(thumb, start + 1); }, 652);
	} else {
		thumb.timerID = setTimeout (function() { rollImages(thumb, start); }, 50);
	}
}

// Create image for imageroll
function rollNewImage(thumb, index) {
	var multi = 1;
	var src = thumb.origimg.split(/[()]/)[1].replace(/"/gm, "");
	if (src.match(/232x157|80x60|153x103/) && !src.match(/PORN\/promo/)) {
		src = src.replace("/promo", "/PORN/promo");
		multi = 2;
	}
	thumb.images[index] = new Image();
	thumb.images[index].src = src.replace(/(promo|sample)_[0-9]+\.jpg/, "promo_" + index * multi + ".jpg");
}

// Define some common action handlers
$(function() {
	// Bookmark
	$("a[href$=#bookmark]").click(function() {
		url = document.location.href;
		title = document.title;
		if (window.sidebar) // firefox
			window.sidebar.addPanel(title, url, "");
			else if(window.opera && window.print){ // opera
			var elem = document.createElement("a");
			elem.setAttribute("href",url);
			elem.setAttribute("title",title);
			elem.setAttribute("rel","sidebar");
			elem.click();
		} else if(document.all)		// ie
			window.external.AddFavorite(url, title);
		return false;
	});
	
	// Skin switcher
	$("p>a.theme").click(function() {
		if ($(this).is(".active")) {
			return false;
		}
		var theme = this.hash.substring(1);
		$(this).addClass("active").siblings("a").removeClass("active");
		$.cookie("theme", theme, { path: "/", expires: 30 });
		if (theme == "dark") {
			var css = $("<link>").attr({ rel: "stylesheet", type: "text/css", href: "/css/members.css" });
			$("head").append(css);
		} else {
			$("head link[rel=stylesheet][href*=members]").remove();
		}
		return false;
	});
	
	// Image roll
	$("ul.listContent.video li a.thumb, li.video a.thumb").live("mouseover", function() {
		rollImages(this);
	}).live("mouseout click", function() {
		clearTimeout(this.timerID);
		this.style.backgroundImage = this.origimg;
	});
	
	// Ratings
	$("div.ratings a.btn").click(function() {
		var link = $(this);
		if (link.siblings("a").andSelf().is(".active")) {
			return false;
		}
		var div = $(this).closest("div.ratings");
		var rating = $(this).is("a.like")? 5 : 1;
		var parts = this.href.split("#")[1].split("_");
		$.post("/ajax/ratings", { type_id: parts[0], item_id: parts[1], rating: rating }, function(data) {
			link.closest("div.ratings").find("span.message").stop().fadeOut("fast", function() { $(this).remove(); });
			link.addMessage(data.message);
			if (data.code == 0) {
				var pc = Math.round(Math.max(0, data.avg_vote - 1) * 25);
				var text = div.find("span.text");
				div.find("div.bar span").css("width", pc + "%");
				text.text(pc + "%" + text.text().split("%")[1]);
				link.addClass("active");
			}
		}, "json");
		return false;
	});
	
	// Favorites
	$("a.btn:has(span.favorite)").click(function() {
		var link = $(this);
		var parts = this.hash.substring(1).split("_");
		$.post("/ajax/favorites", { type_id: parts[0], item_id: parts[1], action: "add" }, function(data) {
			if (data.code == 2) {
				data.message = "Sign up to gain access to this feature";
			}
			link.addMessage(data.message);
			if (data.code == 0) {
				
			}
		}, "json");
		return false;
	});
	
	
	
	// Add comments
	$("div.comment form input:button, div.description form input:button").click(function() {
		var form = $(this).closest("form");
		var body = $.trim(form.find("textarea").val());
		var user = $.trim(form.find("input[name=username]").val());
		var type_id = form.find("input[name=type_id]").val();
		var item_id = form.find("input[name=item_id]").val();
		var rating = form.find("input[name=rating]").val();
		if (body.length < 3 || body.toLowerCase() == "your message...") {
			$.jGrowl("Cannot submit empty comment");
			return false;
		}
		if (user == "" || user.toLowerCase() == "nickname") {
			user = "Anonymous";
		}
		
		// Change the HTML right away
		var p = $("<p>").addClass("thanks").text("Your comment was saved!").prepend("<span>");
		var li = $("<li>").addClass("new")
			.append($("<span>").addClass("vote"))
			.append($("<p>").html('<strong>' + user + ':</strong> <span class="body">' + body.replace(/\n+/g, "<br />") + '</span><span class="date">posted one moment ago</span>'));
		form.find(":visible").remove();
		form.append(p.hide().fadeIn());
		form.next("ul").find("li.none").remove();
		form.next("ul").prepend(li.hide().fadeIn("slow"));

		// Submit request
		var args = { body: body, item_id: item_id, type_id: type_id, username: user, rating: rating, action: "add" };
		$.post("/ajax/comments", args, function(data) {
			if (data.code != 0) {
				$.jGrowl(data.message);
				if (data.code == 7) {
					form.next("ul").find("li:first").remove();
				}
			} else {
				var count = form.prev().find("span");
				count.text(parseInt(count.text()) + 1);
			}
		}, "json");
	});
	
	// Remove comments
	$("ul.showComments li p>a.remove").live("click", function() {
		if (confirm("Remove comment?")) {
			var li = $(this).closest("li");
			var id = li.data("id");
			$(this).remove();
			$.post("/ajax/comments", { action: "edit", comment_id: id, status: -1 }, function(data) {
				$.jGrowl(data.message);
				if (data.code == 0) {
					li.fadeOut("fast", function() { li.remove(); });
				}
			}, "json");
		}
		return false;
	});
	

	// Edit comments
	$("ul.showComments li span.buttons a").live("click", function() {
		var li = $(this).closest("li");
		var action = this.hash.substring(1);
		var id = li.data("id");
		if (action == "approve") {
			var args = { comment_id: id, action: "edit", status: 1 };
			if (!confirm("Approve comment?")) {
				return false;
			}
		} else if (action == "purge") {
			var args = { comment_id: id, action: "remove" };
			if (!confirm("Remove comment permanently?")) {
				return false;
			}
		} else if (action == "reject") {
			var args = { comment_id: id, action: "edit", status: -1 };
			if (!confirm("Reject comment?")) {
				return false;
			}
		} else if (action == "edit") {
			if (li.find("textarea").size() == 1) {
				var text = li.find("textarea").val();
				var args = { comment_id: id, action: "edit", body: text };
				li.find("span.body").text(text);
				li.find("textarea").remove();
			} else {
				var p = li.find("span.body");
				var text = $("<textarea>").attr({ name: text }).text(p.text());
				p.text("").append(text);
				return false;
			}
		}
		$.post("/ajax/comments", args, function(data) {
			$.jGrowl(data.message);
			if (data.code == 0 && (action == "reject" || action == "approve" || action == "purge")) {
				li.fadeOut("fast", function() { li.remove(); });
			}
		}, "json");
		return false;
	});
	
	// Comment ratings
	$("ul.showComments li span.vote a, p.helpful a").live("click", function() {
		var li = $(this).closest("li,div.review");
		var rspan = li.find("span.vote span");
		var rating = $(this).is("[href^=#up]")? 1 : -1;
		var temp = parseInt(rspan.text());
		// Change DOM
		rspan.text((temp + rating) + " Vote" + ((temp == 0)? "" : "s"));
		li.find("span.vote a:first").replaceWith($("<span>").addClass("up" + ((rating == 1)? " active" : "")));
		li.find("span.vote a:last").replaceWith($("<span>").addClass("dn" + ((rating == -1)? " active" : "")));
		// This call requires so confirmation, so just send the Ajax request and forget
		var args = { action: "bump", comment_id: li.data("id"), rating: rating };
		$.post("/ajax/comments", args);
		return false;
	});
	
	// Rating stars
	$("p.starRating a").click(function() {
		var rating = parseInt(this.hash.substring(1));
		$(this).siblings("input").val(rating);
		$(this).addClass("active").siblings("a").removeClass("active");
		return false;
	});
	
	// Comments navigation
	$("a[href$=#next],a[href$=#prev]", "div.comment div.pager").click(function() {
		var pager = $(this).parent();
		if (pager.hasClass("loading")) {
			return false;
		} else {
			pager.addClass("loading");
		}
		var form = pager.closest("div.box.comment");
		var total = parseInt(form.find("div.titleBar span").text());
		var type_id = form.find("input[name=type_id]").val();
		var item_id = form.find("input[name=item_id]").val();
		var change = (this.hash === "#next")? 10 : -10;
		var ul = form.find("ul");
		var offset = ul.data("offset");
		if (typeof offset != "number") {
			offset = 0;
		}
		args = { offset: Math.max(offset + change, 0), limit: 10, type_id: type_id, item_id: item_id, action: "select" };
		if (args.offset == 10) {
			args.offset = 5;
		} else if (args.offset == 0) {
			args.limit = 5;
		}
		
		
		//alert(print_r(args));
		
		$.post("/ajax/comments", args, function(data) {
			var data = $(data).hide().fadeIn();
			parseTimestamps(data);
			ul.html(data).data("offset", args.offset);
			pager.removeClass("loading").children().show();
			pager.children().last().text((args.offset == 0)? "More Comments" : "Next");
			if (args.offset == 0) {
				pager.children().first().hide();
			} else if ((args.offset + 10) >= total) {
				pager.children().last().hide();
			}
		});
		
		
		
		
		
		
//		var link = $(this);
//		var ul = link.prev("ul");
//		if (link.hasClass("collapse") || ul.children().size() > 5) {
//			ul.find("li:gt(4)").fadeToggle();
//			link.find("span.ico").toggleClass("up down");
//			link.toggleClass("collapse");
//		} else {
//			var form = link.closest("div.box.comment").find("form");
//			var type_id = form.find("input[name=type_id]").val();
//			var item_id = form.find("input[name=item_id]").val();
//			$.post("/ajax/comments", { action: "select", offset: 5, type_id: type_id, item_id: item_id }, function(data) {
//				var data = $(data).hide().fadeIn();
//				ul.append(data);
//				link.find("span.ico").toggleClass("up down");
//				link.addClass("collapse");
//				parseTimestamps(data);
//			});
//		}
		return false;
	});
	
	// Sorting options
	$("div.sorting").each(function() {
		var div = $(this);
		$(this).find("span.dropdownContainer>a").mouseenter(function() {
			var options = $(this).next("span");
			this.timerID = setTimeout(function() {
				if (options.size() == 0) {
					div.find("span.dropdownMenu").slideUp("fast");
				} else if ($("span.dropdownMenu:visible", div).size() == 0) {
					options.slideDown("fast");
				} else {
					div.find("span.dropdownMenu").hide();
					options.show();
				}
			}, 200);
		});
	}).mouseleave(function() {
		$("span.dropdownMenu:visible", this).slideUp("fast");
		$(this).find("span.dropdownContainer>a").each(function() {
			if (this.timerID != undefined) {
				clearTimeout(this.timerID);
			}
		});
	});
	

	
//	// Submit custom description
//	$("div.description input:button").click(function() {
//		var form = $(this).closest("form");
//		var args = form.serializeObject();
//		if (args.body.length < 10) {
//			$.jGrowl("Please enter a meaningful description");
//			return false;
//		}
//		args.action = "add";
//		form.find("input:submit").prop("disabled", true);
//		$.post("/ajax/description", args, function(data) {
//			if (data.code == 0) {
//				var p = $("<p>").addClass("thanks").text("Description saved, thanks for making PORN.COM better!").prepend("<span>");
//				form.html("").append(p.hide().fadeIn());
//			} else {
//				$.jGrowl(data.message);
//			}
//		}, "json");
//	});
	
	// Submit report handler
	$("div.box.info.report form input:button").click(function() {
		var form = $(this).closest("form");
		var args = form.serializeObject();
		args.codeName		= navigator.appCodeName;
        args.appName		= navigator.appName;
        args.appVersion		= navigator.appVersion;
        args.platform		= navigator.platform;
        args.userAgent		= navigator.userAgent;
        args.width			= $(window).width();
        args.height			= $(window).height();
        args.language		= getLanguage();
        args.flash			= getFlashVersion();
        args.javaEnabled	= navigator.javaEnabled();
        args.scene_id		= args.item_id;
		$.post("/ajax/report", args, function(data) {
			if (data.code == 0) {
				var p = $("<p>").addClass("thanks").text("Your report was sent! Thank you!").prepend("<span>");
				form.html("").append(p);
			} else {
				$.jGrow(data.message);
			}
		}, "json");
	});

	
	// Login form toggler
	$("#login-link").click(function() {
		$(this).closest("li").toggleClass("active");
		$("div.login").slideToggle("fast"); return false;
	});
	
	// Common toggler links
	$("a[href*='#toggle_']").click(function() {
		var selector = "div.box." + this.hash.split("_").pop();
		var target = $(this).siblings(selector);
		if (target.size() == 0) {
			var target = $(selector).first();
		}
		$(this).toggleClass("active", !target.is(":visible"));
		target.slideToggle("fast");
		return false;
	});
	
	// Common toggler close buttons
	$("div a.close").click(function() {
		$(this).closest("div").slideUp("fast");
		return false;
	});
	$("div.box a.close").click(function() {
		var id = $(this).closest("div.box").attr("class").split(" ").pop();
		var selector = "a.btn[href$='#toggle_" + id + "']";
		var button = $(this).closest("div.box").siblings(selector);
		if (button.size() == 0) {
			button = $(selector);
		}
		button.removeClass("active");
	});
	
	// Actor headshot hover
	$("a.actor").hover(function() {
		var link = $(this);
		var timer = setTimeout(function() {
			link.find("span").fadeIn("fast");
		}, 300);
		link.data("timer", timer);
	}, function() {
		$("span", this).fadeOut("fast");
		clearTimeout($(this).data("timer"));
	});
	
	// Search fields handling
	$("form input:text[name=q]").bind("keyup click", function(e) {
		var field = $(this);
		var code = (e.which == undefined)? 0 : e.which;
		var sgs = field.closest("form").find("div.results");
		var val = $.trim(field.val());
		var total = sgs.find("a").size();
		var t_link = $.trim($(this).siblings("input[name=t_link]").val());
		
		if (code == 40 || code == 38) {
			var index = sgs.find("a.active").removeClass("active").index();
			if (code == 40) { // Down
				if (index < 1 || index == total) {
					index = 1;
				} else {
					index++;
				}
			} else { // Up
				if (index < 2) {
					index = total;
				} else {
					index--;
				}
			}
			sgs.find("a:eq(" + (index - 1) + ")").addClass("active");
		} else {
			sgs.find("a.active").removeClass("active");
		}
		
		
		
//		if (code == 27) {
//			sgs.slideUp("fast");
//		}
		
//		if (this.lastValue == undefined && val.length < 2) {
//			return;
//		}
		
		if (code == 27 || val.length < 2) {
			sgs.slideUp("fast");
			return;
		}
		
		if (val == this.lastValue) {
			if (!sgs.is(":visible") && total > 0) {
				sgs.slideDown("fast");
			}
			return;
		}
		
		if (typeof this.timerID != "undefined") {
			clearTimeout(this.timerID);
		}
		
		this.lastValue = val;
		this.timerID = setTimeout(function() {
			$.post("/search", { q: val, p: 1, limit: 8, t_link: t_link }, function(data) {
				sgs.html(data);
				// Make sure things appear and dissapear as needed
				var results = sgs.children("a").size() > 0;
				var visible = sgs.is(":visible");
				if (results && !visible) {
					sgs.slideDown("fast");
				} else if (!results && visible ){
					sgs.slideUp("fast");
				}
			});
		}, 300);
	});
	$("form.search").submit(function() {
		val = $.trim($(this).find("input[name=q]").val()).toLowerCase();
		if ($(this).find("a.active").size() == 1) {
			window.location = $(this).find("a.active").attr("href");
			return false;
		} else if (val.length < 1 || val == "search porn.com...") {
			return false;
		}
	});
	$("form.search div.results").hover(function() {
		$(this).find("a.active").removeClass("active");
	});
	$("body").click(function(e) {
		if ($(e.target).closest("form.search").size() == 0) {
			$("form.search div.results").slideUp("fast");
		}
	});
	
	// Placeholder hack for IE
	$(":input[placeholder]").focus(function() {
		if ($(this).attr("placeholder") == $(this).val()) {
			$(this).val("");
		}
	}).blur(function() {
		if ($.trim($(this).val()) == "") {
			$(this).val($(this).attr("placeholder"));
		}
	}).blur();
	
	// Email change/resend actions
	$("div.gblAlert a[href*=#], div.gblAlert input:button").click(function() {
		if ($(this).is("a[href$=#update],a[href$=#cancel]")) {
			$(this).siblings().andSelf().toggle();
		} else {
			var div = $(this).closest("p");
			var email = $.trim($(this).siblings("input:text").val());
			$(this).siblings().andSelf().remove();
			div.append("<b>Sending...</b>");
			$.post("/join/resend", { email: email }, function(data) {
				div.find("b").text(data.message);
			}, "json");
		}
		return false;
	});

	// Unroll global message, if present
	setTimeout(function() {
		$("div.gblAlert").slideDown(650);
	}, 900);
});

// Bandwidth check
// Do this when everything else loaded
$(window).load(function() {
	var bw = $.cookie("bandwidth_detected");
	if (bw == null || !parseInt(bw)) {
		getBandwidth();
	}
});













// get locale
function getLanguage() {
    if (typeof(navigator.userLanguage) == "string") {
        return navigator.userLanguage;
    } else if (typeof(navigator.language) == "string") {
        return navigator.language;
    } else {
        return("(Not supported)");
    }
}


function getFlashVersion() { 
	// ie 
	try { 
		try { 
			var axo = new ActiveXObject('ShockwaveFlash.ShockwaveFlash.6'); 
			try { axo.AllowScriptAccess = 'always'; } 
			catch(e) { return '6,0,0'; } 
	   	} catch(e) {} 
		return new ActiveXObject('ShockwaveFlash.ShockwaveFlash').GetVariable('$version').replace(/\D+/g, ',').match(/^,?(.+),?$/)[1]; 
	} catch(e) { 
		try { 
			if(navigator.mimeTypes["application/x-shockwave-flash"].enabledPlugin){ 
				return (navigator.plugins["Shockwave Flash 2.0"] || navigator.plugins["Shockwave Flash"]).description.replace(/\D+/g, ",").match(/^,?(.+),?$/)[1]; 
			} 
		} catch(e) {} 
	} 
	return '0,0,0'; 
}

function print_r(x, max, sep, l) { 
    l = l || 0; 
    max = max || 10; 
    sep = sep || ' '; 
    if (l > max) { 
        return "[WARNING: Too much recursion]\n"; 
    }
    var 
        i, 
        r = '', 
        t = typeof x, 
        tab = ''; 
    if (x === null) { 
        r += "(null)\n"; 
    } else if (t == 'object') { 
        l++; 
        for (i = 0; i < l; i++) { 
            tab += sep; 
        }
        if (x && x.length) { 
            t = 'array'; 
        } 
        r += '(' + t + ") :\n"; 
        for (i in x) { 
            try { 
                r += tab + '[' + i + '] : ' + print_r(x[i], max, sep, (l + 1)); 
            } catch(e) { 
                return "[ERROR: " + e + "]\n"; 
            } 
        } 
    } else { 
        if (t == 'string') { 
            if (x == '') { 
                x = '(empty)'; 
            } 
        } 
        r += '(' + t + ') ' + x + "\n"; 
    } 
    return r; 
};

