/* ************************************************************* */
/* ************************************************************* */
/*           Dynamically Loading Image Navigator                 */
/*         Lovingly hand coded by Lan@MoarPix.com                */
/*      Please DO NOT use this script without permission         */
/*      It's /really/ messy and not suitable for distribution    */
/*						Oct. 31, 2011							 */
/*                                                               */
/*   I'm considering porting it to a regular jQuery plugin       */
/*                    if there's intrest                         */
/* ************************************************************* */

var _$cont, _numItems, _moveby, _cur, _focusPoint;

var _loading = false;
var _curOffset = 0;
var _LoadFail = 0;
var _surplus = [];
var _last = [];
	_last["usr"] = null;
	_last["SiteID"] = null;

$(window).resize(function(){
	Resize();
});

$(document)
	.ready(function(){
		_$cont = $("#ajNav");
		
		$("#ajNContainer")
			.mousewheel(function(event, delta) {
				event.preventDefault();
				event.stopPropagation();
				
				console.log(delta);
				
				var mousePos = delta > 0 ? true : false;
				
				if(mousePos){
					nudge(true);
				}else{
					nudge(false);
				}
			});
			
		$("#barNavHelp .older").click(function(){nudge(false);});
		$("#barNavHelp .newer").click(function(){nudge(true);});
	}); // detect if document scroll while $cunts are moving, if so stop it.
	//.scroll(function(){ console.log('scrolling'); });


function nudge(right,times){
	var n;
	if(times === undefined){var times = 1;}
	if(nudge === undefined){var nudge = true;}
	
	if(right){
		n = _moveby * times;
	}else{
		n = -_moveby * times;
	}
	
	moveCunts(n);
	refreshDisplay();
}

function JumpTo(imgID,myData){
	debug.log("J2 - Called to: "+imgID);
	
	var _defaults = {
		"by" : 35,
		"SiteID" : _SiteID,
		"album" : _AlbumID,
		"usr" : _UserID
	};
	
	if(myData !== undefined){
		var opts = $.extend({},_defaults,myData);
	}else{
		var opts = $.extend({},_defaults,{});
	}
	
	$("#imgDisplay").LoadMsg(false); // for immediate user feedback on click
	
	var $cunts = $(".iContainer");
	//debug.log($cunts);

	if($cunts.length > 0){
		var dCenter = Math.round(_$cont.width()/_moveby);
			
		var $ci = _$cont.children(":nth-child("+dCenter+")");
		var cid = $ci.attr("id"); // bet it's faster than parsing attr(inData) for 'ID'
		cid = cid.substr(1,999);
		debug.log("<----<<<");
		debug.log(cid);
	}

	if((imgID === undefined) || (imgID == "")){
		if($cunts.length > 0){
			imgID = cid;
		}else{
			imgID = "random";
		}
	}
	
	imgID = imgID.toString();
	
	debug.log("J2 - Jumpping to: "+imgID);
	switch(imgID.toLowerCase()){
		case "random":
			//debug.log("J2 - Oh wait, it's random...");
			opts["id"] = "random"
			GrabData({
				"data": opts,
				"init" : true
			});
			JumpTo();
			return;
		break;
		
		case "newest":
			debug.log("J2 - Loading newest...");
			opts["id"] = "newest"
			GrabData({
				"data": opts,
				"init" : true
			});
			//JumpTo();
			return;
		break;
	}
	
	_curOffset = 0;
	var $tCont = $("#c"+imgID);
	if($tCont.length > 0){
		debug.log("J2: Holy shit, it's here!");
		var distance = _focusPoint - $tCont.position().left;

		moveCunts(distance);
		refreshDisplay(imgID);
		return true;
	}else{
		_LoadFail++;
		debug.log("J2: Can't find it. Trying to load data - " + _LoadFail);
		// Blank slider?
		opts["id"] = imgID;
		
		GrabData({
			"data": opts,
			"init": true
		});
		//JumpTo(imgID);
		
		if(_LoadFail > 2){
			nudge();
			// not found msg
			debug.log("J2: Load failed. Max retry exceeded - ci: "+cid);
			//JumpTo(cid);
		}
		
		return false;
	}
}

function refreshDisplay(){
	refreshPicInfo(_cur);
// --------------------------------------------------
/*		var cWidth = _$cont.width();
	var $cunts = $(".iContainer");
	$.each($cunts,function(){
		var $this = $(this);
		var tPos = $this.position()
		
		if(tPos.left > cWidth || tPos.left < 0){
			// Not COMPLETELY in view
			//debug.log("Unseen: "+$this.attr("id"));
			var cid = $this.attr("id");
				cid = cid.substring(1);
		}else{
			// COMPLETELY in view
			var cid = $this.attr("id");
				cid = cid.substring(1);
			//debug.log("InView: "+$this.attr("id"));
		}
	});
	*/
} // -- END refreshDisplay()

function inview(obj, container) {
	if(obj && obj.jquery){$obj = obj;}else{var $obj = $(obj);}
	if(container && container.jquery){$container = container;}else{var $container = $(container);}

	tPos = $obj.position();
	//debug.log(tPos);
	//debug.log($container);
	if(tPos.left > $container.width() - _moveby || tPos.left < 0){
		// Not COMPLETELY in view
		return false;
	}else{
		// COMPLETELY inview
		return true;
	}
}

function moveCunts(distance){
// distance always = a multiple of _moveby
	//if(_loading){return false;}
	_surplus["before"] = 0; _surplus["after"] = 0;
	
	var Buffer = [];
		Buffer["low"] = 3;
		Buffer["Restock"] = 10;
		Buffer["max"] = Buffer["Restock"] * 5;
		
	var $cunts = $(".iContainer");
	var $fst = _$cont.children(":first");
	var $lst = _$cont.children(":last");

	var $ajC = $("#ajCursor");
	var nd = _focusPoint - distance; // ...
	
	//debug.log("_fP: "+_focusPoint+" dist: "+distance+"  = nd: "+nd+" || _mb: "+_moveby+" _$c.w: "+_$cont.width()+" - _nI: "+_numItems);
	
	if(!_loading){
		if(distance > 0){ // Why does everything in this project have to be such a bitch?
			if(inview($fst, _$cont)){
				nd += distance;
				distance = 0;
				
				var Fid = $fst.attr("id"); // bet it's faster than parsing attr(inData) for 'ID'
					Fid = Fid.substring(1);
				
				if(_cur != Fid){ // end of the line
					_curOffset += 1;
				}
				
				if(_curOffset < 0){
					nd += distance;
					distance = 0;
					
					_curOffset += 1;
				}
			}
			
		}else{	
			if(inview($lst, _$cont)){
				nd += distance;
				distance = 0;
				
				var Fid = $lst.attr("id"); // bet it's faster than parsing attr(inData) for 'ID'
				Fid = Fid.substring(1);
				
				if(_cur != Fid){ // end of the line
					_curOffset -= 1;
				}
			}
			
			if(_curOffset > 0){
				nd += distance;
				distance = 0;
				
				_curOffset -= 1;
			}
		}
	}else{_curOffset = 0;}

	//debug.log("!???? _curOffset: "+_curOffset);
	var i=0;
	if($cunts.is(":animated")){$cunts.each(function(){$(this).stop(false,true);});}
	
	$.each($cunts,function(){
		var $this = $(this);
		
		var tLeft = $this.position().left;
		var nLeft = tLeft + distance;
		//debug.log(tLeft+": tL - nd: "+nd);
		
		if(nLeft < nd){_surplus["before"]++;}
		if(nLeft > nd){_surplus["after"]++;}

		var cid = $this.attr("id"); // bet it's faster than parsing attr(inData) for 'ID'
			cid = cid.substring(1);
		
		if(Math.round(tLeft) == (Math.round(nd) - (_moveby * _curOffset))){ // New active item
			_cur = cid;
			$this.addClass("active");
			$ajC.css({"left":nd}); // Cursor
		}else{
			$this.removeClass("active");
		}
		//.stop(true,true)
		$this.animate({left: nLeft});
		i++;
	});
	//debug.log("MoveCunts() - nd: "+nd+" -=- NI: "+_numItems+" - cL: "+centerLine+" - _fP: "+_focusPoint);
	
	///////////////////////
	// Low Stock check
	
	if(_surplus["after"] <= Buffer["low"]){ // see if we're running out of items to the left
		if($lst.attr("id") != "cEND"){
			var end = $.parseJSON($lst.attr("inData"));
			$("#_preload").text("after").show();
			
			GrabData({
				"data":{
					"id" : end["ID"],
					"by" : Buffer["Restock"],
					"trending": "after",
					"SiteID" : _SiteID,
					"usr" : _UserID
				},
				"before" : false
			});
		}
	}
	
	if(_surplus["before"] <= Buffer["low"]){ // see if we're running out of items to the left
		if($fst.attr("id") != "cEND"){
			var end = $.parseJSON($fst.attr("inData"));
			$("#_preload").text("before").show();
			
			GrabData({
				"data":{
					"id" : end["ID"],
					"by" : Buffer["Restock"],
					"trending": "before",
					"SiteID" : _SiteID,
					"usr" : _UserID
				},
				"before" : true
			});
		}
		
	}
	///////////////////////
	// Surplus Check
	if(_surplus["after"] >= Buffer["max"]){ // see if we're running out of items to the left
		var excess = _surplus["after"] - Buffer["max"];
		if(excess > 0){
			//debug.log("after excess: "+excess );
			for(var i=0;i<excess;i++){
				_$cont.children(":last").remove();
			}
		}
	}
	
	if(_surplus["before"] >= Buffer["max"]){ // see if we're running out of items to the left
		var excess = _surplus["before"] - Buffer["max"];
		if(excess > 0){
			//debug.log("before excess: "+excess );
			for(var i=0;i<excess;i++){
				_$cont.children(":first").remove();
			}
		}
	}
	
}
	
function Resize(){
	var dCenter = Math.round(_$cont.width()/_moveby);
	_focusPoint = Math.round(((dCenter - (Math.round(dCenter/2))) * _moveby));
}
	
function GrabData(args){
	// this should be changeable with a callback to alow other methods of grabbing data
	var _defaults = {
		"url" : "/sites/titsplz/imgNav.php",
		"before" : false,
		"init" : false,
		"data" : {} 
	};

	var opts = $.extend({},_defaults,args);
	//debug.log("GrabData data --v");
	//debug.log(opts);
	
	if(opts["init"]){ // Clear the canvas of any old containers
		$cunts = $(".iContainer");
		$cunts.remove();
		_loading = false;
	}
	
	if(_loading){
		debug.log("... preload in progress - aborting.");
		return null;
	}
	_loading = true; // <-- ...
	
	//debug.log("::_SiteID: " + _SiteID);
	//debug.log("::_Usr: " + _SiteID);
	
	$.each(opts["data"], function(k,val){
		if(val === null){
			delete opts["data"][k];
		}
	});
	
	$.ajax({
		url:		opts["url"],
		data:		$.extend({"json":""},opts["data"]),
		
		async:		false,
		cache:		false,
		timeout:	(5*1000),
		dataType:	"JSON",
		
		error:		function(XMLHttpRequest, textStatus, errorThrown){
						debug.log("GDError: "+textStatus+": \n"+errorThrown);
					},
					
		success:	function(data, textStatus, XMLHttpRequest){
							_loading = true;
							
							var newItems = data;
							//debug.log("!!!!!!!!!!!!--GrabData");
							//debug.log("Adding these items --v");
							//debug.log(newItems);
							
							//var rndColor = "#"+Math.floor(Math.random()*16777216).toString(16); // to make it easier to see the new stuff that loads
							
							$("#PTime").text(data["timer"]);
							
							if(newItems["data"].length > 0){
								var i = 0;
								var margin = 5;
								var appendOffset = 0;
								
								var $cunts = $(".iContainer");
								if($cunts.is(":animated")){$cunts.each(function(){$(this).stop(false,true);});}
								
								$.each(newItems["data"], function (){
									var tmp = this, hasRun = false;
									var jstmp = $.toJSON(tmp);
									var fan = '';

									if(tmp["Caption"] == null){tmp["Caption"] = "&nbsp;";}
									//var bottombar = "<div class='bottombar'><span class='views' title='"+tmp["Hits"]+" views. "+tmp["HitsToday"]+" of those were from today'><img src='/images/toy/view-ico.gif'>: "+tmp["Hits"]+"</span>"+tmp["Caption"]+"<span class='rating' title='Rated "+tmp["Rating"]+" from "+tmp["RatingCount"]+" voters'>"+tmp["Rating"]+" :<img src='/images/toy/TUp.gif' style='height:10px;'></span></div>";
									var bottombar = "<div class='bottombar'>"+tmp["ID"]+"</div>";
									
									if(tmp["Fan"] == 1){fan = "<div class='fan'></div>";}
									
									var newItem = "<div id='c"+tmp["ID"]+"' class='iContainer'>"+fan+"<img class='thumbnail' src='/tn/?sm"+tmp["ID"]+tmp["ext"]+"'/>"+bottombar+"</div>";
									//debug.log(_$cont);
									if(opts["before"]){
										_$cont.prepend(newItem);
									}else{
										_$cont.append(newItem);
									}
									
									var $nc = $("#c"+tmp["ID"]);
									
									if(opts["init"]){
										_moveby = $nc.width() + margin;
									}
									
									var L = 0;
									if(opts["before"]){ // You have no idea how long it took to get these lines to work right.
										if(!opts["init"]){
											var $fst = _$cont.children(":first");
											L =  $fst.position().left - _moveby + (i*-_moveby);
										}else{
											L = (i*-_moveby);
										}
									}else{
										if(!opts["init"]){
											var $lst = _$cont.children(":last").prev();
											//debug.log("LstLEft: "+$lst.position().left+" <======-----------------");
											L =  $lst.position().left + _moveby ; 
											
											//$nc.css({"border": "2px solid "+rndColor});
										}else{
											L = (i*_moveby);
										}
									}
									
									//debug.log("i: "+i+" L: "+L+" - _init: "+opts["init"]+" before: "+opts["before"]+" mb: "+_moveby);
									
									$nc
										.css({left : L})
										.LoadMsg(true)
										.attr("inData",jstmp)
										.children(".thumbnail").load(function () {
											var $th = $(this);
											
											if($th.width() < $th.height){
												$th.height($nc.height());
											}else{
												$th.width($nc.width());
											}
											
											$th.css({
												top: Math.round(($nc.height() - $th.height()) / 2),
												left: Math.round(($nc.width() - $th.width()) / 2)
											})
											
											$th.fadeIn(500, "linear");
											$nc.LoadMsg(false);
										})
										.hover(
											function() { // over 
												$nc.children(".bottombar").stop(true,true).fadeTo("slow",0.8)
											},
											function (){ // out
												$nc.children(".bottombar").stop(true,true).fadeOut();
											}
										)
										.click(function(){
											JumpTo(tmp["ID"]);
											//refreshPicInfo(tmp["ID"]);
										});
									i++;
								});
								
								_numItems = $(".iContainer").length;
								
								if(opts["init"]){
									Resize();
									
									var od = opts["data"]["id"];
									//debug.log(od);
									if(od != null){
										switch(od.toLowerCase()){
											case "random":
												nudge(false,Math.ceil(_numItems/2));
												debug.log(_numItems);
											break;
											
											case "newest":
												nudge(true,2);
											break;
											
											default:
												var inData = $.parseJSON($("#c"+od).attr("inData"));
												_SiteID = inData["SiteID"];
												//_UserID = inData["OwnerID"];
												debug.log("INDATA");
												debug.log(inData);
												
												debug.log(od);
												if(od == inData["ID"]){
													JumpTo(od);
												}else{
													JumpTo();
												}
											break;
										}
									}
								}
							}else{
								debug.log("No results. opts follow --v");
								debug.log(opts);
							}
							
							_loading = false;
							$("#_preload").fadeOut();
					}
	});
}
		
/*
	var ret = [];
	$.getJSON('https://ajax.googleapis.com/ajax/services/search/images?q=puppies+kittens&v=1.0&callback=?', 
		function(data) {
			debug.log(data);
			
			$.each(data["responseData"]["results"], function(){
				var tmp = [];
				//debug.log(this);
				tmp["tnURL"] = this["tbUrl"]
				tmp["Caption"] = this["titleNoFormatting"]
				
				ret.push(tmp);
				
				
			});
		//	return data;
		}
	);

	return ret;
*/
