(function($){
// debug levels
// 0: no debug
// 1: debug function call order
// 2: debug list sorting process
// 3: debug list rendering process
	
$.fn.portfolio = function(options){
	var settings = {
		baseurl: "ramp.rovion.com",
		debug:0
	}
	$.extend(settings,options);
	settings.baseurl = "ramp.rovion.com"
	var preloadImg = new Image();
	preloadImg.src = "http://"+settings.baseurl+"/css/ajax-loader.gif";
	
	var isdebug = function(level){
		 return settings.debug == level || settings.debug == 9
	}
	
	var controller = {
		init : function(context){
			if(isdebug(1)) console.info("Controller : init called",context);
			window.portfoliolayout = function(data){
				data = data.output;
				$(context).html(data);
				model.quicksand.init(context);
				$(context).find(".tags input").click(function(){
					if($(context).find(".portfolio-list").length > 0){
						window.location = "#list";
						controller.list(context);
					}
				});
				$(context).find(".cat-item").click(function(){
					$(this).parent().find("a.selected").removeClass("selected");
					$(this).find("a").addClass("selected");
					window.location = "#list";
					controller.list(context);
				});
				context.router.ready = true;
				context.router.route(true);
				if(isdebug(1)) console.info("Controller : init end callback");
			}
			$.ajax("http://"+settings.baseurl+"/portfolios/layout",{
				success:function(data){
					
				},
				dataType:"script"
			});
			if(isdebug(1)) console.info("Controller : init ended");
		},
		index : function(context,options){
			if(isdebug(1)) console.info("Controller : index called",context,options);
			this.list(context,options);
			if(isdebug(1)) console.info("Controller : index ended");
		},
		list : function (context,options){ // THIS FUNCTION HANDLES LIST FUNCTIONALITY
			if(isdebug(1) ) console.info("controller : list being called",context,options);
			clearInterval(context.data.listInterval);
			if(typeof(context.data.listdata) == "undefined"){
				return model.getListData(context,controller.list,options);
			}
			var j,body,src,img,container,onclick,labellist = [], listdata = context.data.listdata,tags,
				resultList = [],returncondition = false;
			
			// sort through listdata
			if(isdebug(2)) console.clear();
			for(var i = 0; i < listdata.length; i++ ){
				returncondition = false;
				tags = model.getSelectedTags(context);
				for(j = 0; j < tags.length; j++){
					if(listdata[i][0][tags[j]] == 1){
						returncondition = true;
					}
				}
				buf = returncondition;
				
				j = $(context).find(".cat-item a.selected:first").html();
				if(typeof(j) == "undefined") j = "";
				if(isdebug(2)) console.debug("Gathered Filter Value: ",j);
				
				if( j.toLowerCase() == "any") returncondition == returncondition || true; 
				else if( listdata[i][0].labels ) {
					returncondition =  returncondition && ($.inArray(j,listdata[i][0].labels.split(",")) != -1  || j == "" || typeof(j) == "undefined");
					if(isdebug(2)) console.debug(listdata[i][0].labels.split(","),i,listdata[i].Addemo.id,j,$.inArray(j,listdata[i][0].labels.split(",")));
				} else if(typeof(listdata[i][0].labels) == "undefined" && j != ""){
					returncondition = false;
					if(isdebug(2)) console.debug("No Labels",i,listdata[i].Addemo.id)
				}

				if(returncondition){
					resultList.push(listdata[i]);
					if(isdebug(2)) console.info("Accepted:",listdata[i],listdata[i][0].labels);
				} else {
					if(isdebug(2)) console.warn("Rejected:",listdata[i],listdata[i][0].labels);
				}
				
				if( listdata[i][0].labels ){
					for( j = 0; j < listdata[i][0].labels.split(",").length; j++){
						labellist.push(listdata[i][0].labels.split(",")[j]);
					}
				}
			}
			listdata = resultList;
			if(isdebug(2)) console.info(listdata);
			
			/*
			var $L = $("select[name=labels]",context);
			if($L.hasClass("updated") == false){
				var val = $L.val();
				
				var first = $L.find("option:first").get(0);
				$L.html("").append(first);
				for(i = 0; i < $.unique(labellist).length; i++){
					$("<option>").html($.unique(labellist).sort()[i]).appendTo($L.get());
				}
				$L.addClass("updated");
			}
			*/
			if($(".portfolio-body .portfolio-list",context).length == 0) $(".portfolio-body",context).html("<h1>Ad Showcase</h1>");
			body = $("<div>").addClass("portfolio-list").appendTo($(context).find(".portfolio-body").get(0))
				.data("listdata",listdata).get(0);
			$("<div>").css({clear:"both"}).insertAfter(body);
				
			var renderListItem = function(context,i,listdata){  // RENDERS THE INDEVIDUAL LIST ITEMS
				if(isdebug(3)) console.info("renderListItem called:",context,i,listdata[i]);
				src = "http://"+settings.baseurl+"/addemos/demo_thumb/"+listdata[i].Addemo.id+"/144";
				
				container = $("<div>").addClass("portfolio-item").click(function(){
					window.location = "#detail/index:"+$(this).data("id");
				}).data("local_url",listdata[i].Addemo.local_url)
					.data("index",i).attr("title",listdata[i].Portfolio.name).get(0);
				a = $("<a>").attr("href","#detail/index:"+listdata[i].Portfolio.id).appendTo(container).get(0);
				$("<img>").attr({"src":src,valign:"top"}).appendTo(a);
				$("<div>").addClass("portfolio-title").html("<h2>"+listdata[i].Portfolio.name+"</h2>").appendTo(a);
				model.quicksand.add(context,listdata[i].Portfolio.id,container);
				// if((i + 1) % 3 == 0) $("<div>").css({clear:"both"}).appendTo(body);
			}
			model.quicksand.clear(context);
			for( i = 0; i < listdata.length  && i < 18; i++){
				renderListItem(context,i,listdata);
			}
			$("<div>").css({clear:"both"}).appendTo(body);
			
			context.data.listInterval = setInterval(function(){ // HANDLES THE DYNAMIC SCROLL PAGINATION FUNCTIONALITY
				$(context).find(".portfolio-quicksand-list").each(function(){
					if(isdebug(3)) console.info("list pagination interval triggered");
					var listPosition = $(this).offset().top;
					var listHeight = $(this).height();
					var winPosition = $(window).scrollTop();
					var winHeight = $(window).height();
					if(isdebug(3)) console.debug("'should I render' conditional: ",
						listPosition + listHeight - winPosition - winHeight < 600,
						listPosition,listHeight,winPosition,winHeight,
						listPosition + listHeight - winPosition - winHeight);
					if(listPosition + listHeight - winPosition - winHeight < 600){
						var lastIndex = $(".portfolio-item:last").data("index");
						var hasRendered = false;
						for(var i = lastIndex + 1; i <= lastIndex + 3 && i < listdata.length; i++){
							renderListItem(context,i,listdata);
							hasRendered = true;
						}
						if(hasRendered)model.quicksand.update(context);
					}
				});
			},context.router.routeInterval);
			model.quicksand.update(context);
			if(isdebug(1) ) console.info("controller : list ended");
		},
		helloworld: function(context,options){
			alert("Hello World! \n"+options.message);
		},
		detail: function(context,options){
			if($(context).find(".portfolio-body .portfolio-quicksand-list").length == 0 ) controller.list(context);
			if(isdebug(1) ) console.info("controller : detail being called",context,options);
			if(typeof(context.data.listdata) != "object") return model.getListData(context,controller.detail,options);
			var detailSettings = { index: 0 };
			$.extend(detailSettings,options);
			var url = "http://"+settings.baseurl+"/portfolios/detail/"+detailSettings.index
			window.portfoliodetail = function(data){
				if(typeof(data) != "object") data = eval("("+data+")");
				data = data.output;
				
				$.colorbox({html:data,onOpen:function(a){
					setTimeout(function(){
						$("#cboxClose").html("");
					},200);
				}});
				
				if(false)$(context).find(".portfolio-body").html(data).find(".close").css({
				});
				if(isdebug(1) ) console.debug("controller : detail being called",context,options);
			}
			$.ajax(
				url,{
				dataType: "script",
				success:function(data){
				}
			});
			if(isdebug(1) ) console.info("controller : detail ended");
		}
	}
	
	var model = {
		getSelectedTags : function(context){
			var taglist = [];
			$(".tags input[type=checkbox]:checked").each(function(){
				taglist.push($(this).attr("name"));
			});
			return taglist;
		},
		setLoadingAnimation : function(context){
			var body = $(context).find(".portfolio-body").html("").get(0);
			$("<img>").attr("src","http://"+settings.baseurl+"/css/ajax-loader.gif").css({
				display:"block",padding:"100px",margin:"auto"
			}).appendTo(body);
		},
		getListData : function(context,callback,options){
			window.portfoliolist = function(data){
				if(typeof(data) != "object"){
					data = eval( "(" + data + ")" );
				}
				if(isdebug(2)) console.debug(data);
				context.data.listdata = data;
				callback(context,options);
			}
			$.ajax("http://"+settings.baseurl+"/portfolios/listdata",{
				success:function(data){
				},
				error:function(){
					// alert("errror");
				},
				complete:function(){
					// alert("complete");
				},
				dataType:"script"
			})
			return;
		},
		makeUnique: function(element){
			var idPool = [];
			$(element).find("li").each(function(){
				var id = $(this).attr("data-id");
				if($.inArray(id,idPool) > -1){
					$(this).remove();
					return;
				}
				idPool.push(id);
			});
		},
		quicksand: {
			init : function(context){
				$("<ul>").addClass("portfolio-quicksand").appendTo(context).css("display","none");
				
			},
			clear : function(context){
				$(".portfolio-quicksand",context).html("");
				return model.quicksand;
			},
			add : function(context,id,element){
				if($(".portfolio-quicksand",context).length == 0){
					console.warn("Quicksand Modal re-initialized");
					model.quicksand.init(context);
				}
				if(isdebug(3))console.debug(
					"Entry Added:",		id,		element,
					$(".portfolio-quicksand",context).get(0),
					$(".portfolio-quicksand",context).children().length);
				$("<li>").appendTo($(context).find(".portfolio-quicksand").get(0)).html(element).attr("data-id",id);
				return model.quicksand;
			},
			update : function(context){ // THIS FUNCTION MAKES QUICKSAND WORK WITH THE LIST FUNCTIONALITY
				model.makeUnique($(context).find(".portfolio-quicksand").get(0));
				if($(context).find(".portfolio-quicksand-list").length == 0){
					if(isdebug(2)) console.info("Creating portfolio quicksand list");
					$("<ul>").addClass("portfolio-quicksand-list").appendTo($(context).find(".portfolio-body").get(0));
				} else {
					$(".portfolio-body ul:first");
				}
				
				if(isdebug(2)){
					console.log("Quicksand Interval Trigger,");
					console.debug($(".portfolio-quicksand-list"),$(".portfolio-quicksand"),context);
				}
				$(".portfolio-quicksand-list").quicksand(".portfolio-quicksand li");
				
				return model.quicksand;
			}
		}
	}
	
	var router = function(context){
		context.data = {};
		var thisRouter = this;
		context.router = this;
		this.context = context;
		this.hash = "blarg.";
		this.history = [];
		this.routeInterval = 800;
		this.model = model;
		this.ready = false;
		
		this.route = function(force){
			var newHash = window.location.hash;	
			if(thisRouter.hash == newHash && force !== true) return thisRouter;
			
			thisRouter.history.push(thisRouter.hash);
			thisRouter.hash = newHash;
			
			if(typeof(window.location.hash) == "undefined" || window.location.hash.length == 0){
				controller.index(context);
				return thisRouter;
			}
			
			var rawHashArgs = newHash.split("/");
			var hashArgs = {};
			var method = rawHashArgs[0].replace("#","");
			
			for( var i = 1; i < rawHashArgs.length; i++){
				hashArgs[rawHashArgs[i].split(":")[0]] = rawHashArgs[i].split(":")[1];
			}
			if(settings.debug >= 2) console.debug(method,hashArgs);
			if(typeof(controller[method]) != "undefined") controller[method](context,hashArgs);	
			else controller.index(context,hashArgs);
			
			return thisRouter;
		}
		
		controller.init(context);
		setTimeout(function(){
			setInterval(thisRouter.route,thisRouter.routeInterval);
		},2000);
	}
	
	
	document.routers = [];
	this.each(function(){
		document.routers.push((new router(this)));
	});
	
	
}
})(jQuery);


