/**
 * Module object takes the place of the Module jquery widget. Module.function() available to each module
 */
var Module = {
	init:function (target) {
		// 1. Module base functions
		// 2. Custom functions for specific modules
		return this;
	},
	
	autocolumn:function(target) {
		Module.MultiColumnFlow.init();
		return;
	},
	
	inlinemenu:function(target) {
		$("div.questions ul li a",target).click(function(e) {
			//Device.log(($($($(this).attr("href"))[0]).position().left+100)/$("section").width());
			var t = $($($(this).attr("href"))[0]);
			Page.scroller.scrollToTarget(-t.position().left, 0);
			//Page.scroller.setValue((t.width() + t.position().left)/$("section").width(),0,false)
			return false;
		});
		
		$("div.answers ul li.back",target).click(function(e) { Page.scroller.setValue(0, 0, false); });		
	},
	
	toggle: function(target, button, onClick, onCancel) {
		if(button) button.find("a").click(function(e) {  });
		((button) ? button : $("a.toggle",target)).click(function(e) {
			var isHiding = ($(this).siblings(".expandable").css("display") == "none");
			
			$(".expandable").hide();// hide all expandables
			if(isHiding)  $(this).siblings(".expandable").show();
			if(onClick && typeof(onClick) == "function") onClick($(this));
			
			
			return false;
		});
				
		$(".expandable li.toggle-cancel",target).click(function(e) {
			$(this).parents(".expandable").hide();
			if(onCancel && typeof(onCancel) == "function") onCancel($(this));
			return false;
		});
	},
	
	flag:function(target) {
		var t = $(".flag li.toggle-confirm",target);
		t.click(function(e) { $("form#flag_form").submit(); });
		
		$("form#flag_form").submit(function(e) {
			t.find("a").html("Submitting...");
			$(".action-menu .favorite-loader").fadeIn(500);
			$.post(t.attr("action"),t.serialize(), function(data) {
				t.attr("href","#").find("a").html("Flagged!");
				$(".action-menu .favorite-loader").fadeOut(500);
				$(".flag",target).parents(".expandable").delay(1000).fadeOut(500, function() {
					t.siblings('.toggle-cancel').appendTo($("ul.flag",target)).css("margin-top","0").find("a").html("Flagged!");
					t.parent().remove();
				});
			});
			return false;
		});
	},
	
	expand: function(target) {
		
		$(".expand").live("mouseover mouseout", function(event){
			if (event.type == "mouseover"){
				$(this).siblings(".expandable").show();
			}else if (event.type == "mouseout"){
				$(this).siblings(".expandable").hide();
			}
		});
		
		$(".expandable").live("mouseover mouseout",function(event){
			if(event.type == "mouseover"){
				$(this).show();
				$(this).siblings(".poptags").addClass("highlight");
			}else if(event.type == "mouseout"){
				$(this).hide();
				$(this).siblings(".poptags").removeClass("highlight");
			}
		});
	},
	
	/**
	 * Append empty list items to fill the space if a list isn't complete
	 * @param ul - jquery main list item
	 * @param total - number of TOTAL items in this list (so if there's 8 total and only 3 <li>'s exist, this will generate 5 empty <li>'s
	 */
	append_empty_gallery: function(li,total, nextbtn) {
		for(var i = li.length; i < total; i++) {
			li.parent().append('<li/>');
		}
	},
	
	traydress: function(li) {
		//var a = li.find("a").bind("mouseover", function(event){
		li.bind("mouseover", function(event){
			if (!$(this).data('init')) {
				$(this).data('init', true);
				$(this).hoverIntent(
					Module.traydress_mouseover,
					function() { /* mouseout logic */ }  
				);
				$(this).trigger('mouseover');
			}
		});
	},
	
	traydress_mouseover:function (e,li) {
		li = (li) ? li : $(this);
		li.parents(".module").css("zIndex", 1000);
		li.parents(".thumbs").css("zIndex", 1000);
		
		// Fix for "browser jumping" in IE 7..
		if($.browser.msie && $.browser.version < 8.0){
			li.parents(".thumbs.movement").css("position", 'absolute');
		}
		
		$(".traydress").remove(); // clear all traydresses
		
		pos =li.position();
		topAdjustment = ((li.offset().top <= 160) ? 25 : ((li.offset().top >= 460) ? 78 : 45)); // 501 153
		
		var traydress = $("<div/>").appendTo(li.parents(".thumbs")).addClass("traydress");
			traydress.html("<div class=\"icon details\" />"+li.html()).css({left:pos.left-55,top:pos.top-topAdjustment})
			
			var img = $("img",traydress);
			var photo = img.parent().wrap('<div class="photo"/>').parent();
			img.css({"left":((photo.width()-img.width())/2),"top":((photo.height()-img.height())/2),"width":"auto", "height":"auto"}); // clear the img positioning
			
			var style = {width:180, height:150}; // hard coded because reading off stylesheet doesnt work...
			var ro = (style.width/style.height); // orig ratio
			var rp = (img.width()/img.height())
			if(rp < ro) img.css("width",style.width); // scale to width and height will crop  
			else img.css("height",style.height);
			img.css({"left":(style.width-img.width())/2, "top":(style.height-img.height())/2}); // center the result
			
			
			if(traydress.offset() && traydress.offset().left < 0) { traydress.css("left",pos.left-25); }			
			traydress.bind("mouseout",function(event) {
				li.parents(".module").css("zIndex", 0); $(this).remove(); 
				li.parents(".thumbs").css("zIndex", 3);
				
				// Fix for "browser jumping" in IE 7..
				if($.browser.msie && $.browser.version < 8.0){
					li.parents(".thumbs.movement").css("position", 'relative');
				}
			});
			
	},
	
	/**
	 * @param target ul list object
	 * @param transitionIn function to run on load
	 */
	transition_image:function(img, transitionIn) {
		img.hide().each(function(index,value) {
			if($(this)[0].complete) transitionIn($(this),index);
			else $(this).load( function() { transitionIn($(this),index) });
		});
	},
	
	pagination:function(target,type,template) {
		if(template) {
			// 2 extend to load more images functionality 
			$(".extend",target).click(function(e) {
				$(".loader",$(this)).show();
				$.get($(this).find("a").attr("href"), function(data) {
					if(data) {
						var page_data = data.response[type].page_data;
						var list = data.response[type].object_list;
						if(parseInt(page_data.current_page) < parseInt(page_data.page_count)) {
							$(".extend", target).appendTo(target).find(".loader").hide();
							Module.update_anchor_value('page', $(".extend a", target),(page_data.current_page +1) );
						} else { $(".extend",target).remove(); }
						
						template(target,list);
						Page.reset();
					}
				});
				return false;
			});
		}
	},
	
	update_anchor_value:function(needle, anchor, newvalue) {
		needle = '"'+needle+'":"';
		var href = anchor.attr("href");
		var start = href.indexOf(needle);
		var end = href.indexOf('"',start+needle.length)
		var new_href = href.substring(0,start+needle.length) + newvalue + href.substring(end);
		anchor.attr("href",new_href);
	},
	
	/* flow a <li> horizontally by breaking it up into <ul>s */
	columnize:function(target) {
		$("ul.columnize", target).each(function() {
			var classes = $(this).attr('class').split(' ')
			var numRows = Device.getClassValue(classes,"numRows");
			if(!numRows) return;
			
			var skipRows = Device.getClassValue(classes,"skipRows");
			var totalRows = Math.ceil( $("> li",$(this)).length / numRows);
			for(var i = 0; i < totalRows; i++) {
				if($("> li",$(this))[skipRows]) {
					var ul = $("<ul/>").appendTo($(this).parent());	// split into multiple lists
					for(var i2 = skipRows + (i*numRows); i2 < skipRows + ((i+1)*numRows); i2++) {
						ul.append($("> li",$(this))[skipRows]); // appending removes from array, so its poping them off the array
						ul.addClass("columnized");
					}
				}
			}
			if(!skipRows) $(this).remove();
			else $(this).removeClass().addClass("columnized");
		});
	},
	
	/* Format Twitter Time */
	format_time: function (time_value) { // pulled from twitter blog js
	  var values = time_value.split(" "); time_value = values[1] + " " + values[2] + ", " + values[5] + " " + values[3]; var parsed_date = Date.parse(time_value); var relative_to = (arguments.length > 1) ? arguments[1] : new Date(); var delta = parseInt((relative_to.getTime() - parsed_date) / 1000); delta = delta + (relative_to.getTimezoneOffset() * 60);
		if (delta < 60) { return 'less than a minute ago'; } else if(delta < 120) { return 'about a minute ago'; } else if(delta < (60*60)) { return (parseInt(delta / 60)).toString() + ' minutes ago'; } else if(delta < (120*60)) { return 'about an hour ago'; } else if(delta < (24*60*60)) {
		return 'about ' + (parseInt(delta / 3600)).toString() + ' hours ago'; } else if(delta < (48*60*60)) { return '1 day ago'; } else { return (parseInt(delta / 86400)).toString() + ' days ago'; }
	},
	
	/* checks to see if 2 points of rectangle are within visible screen area */
	is_visible:function(target) {
		if(!$(target.selector).length) return false; // target no longer exists
		var eb = { x1:target.offset().left,x2:target.offset().left+target.width(),y1:target.offset().top,y2:target.offset().top+target.height()} //element bounds
		var b = { x1:$(window).scrollLeft(), x2:$(window).scrollLeft()+$(window).width(),y1:$(window).scrollTop(),y2:$(window).scrollTop()+$(window).height()};// window bounds
		var pass = 0;
		if(b.x1 <= eb.x1 && eb.x1 <= b.x2 && b.y1 <= eb.y1 && eb.y1 <= b.y2 ) pass++; // x1,y1 top left
		if(b.x1 <= eb.x2 && eb.x2 <= b.x2 && b.y1 <= eb.y1 && eb.y1 <= b.y2 ) pass++; // x2,y1 top right
		if(b.x1 <= eb.x2 && eb.x2 <= b.x2 && b.y1 <= eb.y2 && eb.y2 <= b.y2 ) pass++; // x2,y2 bottom right
		if(b.x1 <= eb.x1 && eb.x1 <= b.x2 && b.y1 <= eb.y2 && eb.y2 <= b.y2 ) pass++; // x1,y2 bottom left
		return (pass>= 2); // 2 points or move visible
	}
}

Module.MovementGallery = {
	
	init: function(target) {
		var thumbs = $(".thumbs ul li.thumb",target)
		Module.append_empty_gallery(thumbs,22);
		Module.traydress(thumbs); // add traydress rollover
		Module.transition_image($("img",thumbs), Module.GalleryRelated.transitionIn); // resize and transition images
		
		$(".expand",target).live("mouseover mouseout", function(event){
			if (event.type == "mouseover"){
				if($($(this).siblings(".expandable")[0]).css('display') != "block"){
					$(this).siblings(".expandable").show();
					$(this).addClass("highlight");
				}
			}else if (event.type == "mouseout"){
				if($($(this).siblings(".expandable")[0]).css('display') == "block"){
					$(this).siblings(".expandable").hide();
					//$(this).removeClass("highlight");
				}
			}
		});
		
		var expandHideIntID;
		
		$("li.browse").mouseover(function(event) {
			
			//$(this).show().find(".poptags").addClass("highlight");
			if($($(this).find(".expandable")[0]).css('display') != "block"){
				$(this).find(".expandable").show();
				$(".poptags").addClass("highlight");
			}
			clearInterval(expandHideIntID);
			$(".filters",target).css("z-index","5");
		}).mouseout(function(event){
			
			if($($(this).find(".expandable")[0]).css('display') == "block"){
				expandHideIntID = setInterval('$(".expandable").hide();$(".poptags").removeClass("highlight")', 200);
				$(".filters",target).css("z-index","4");
			}
			
		});
		
		/*
		$(".expandable",target).live("mouseover mouseout",function(event){
			if(event.type == "mouseover"){
				$(this).show();
				$(this).siblings(".poptags").addClass("highlight");
			}else if(event.type == "mouseout"){
				$(this).hide();
				$(this).siblings(".poptags").removeClass("highlight");
			}		
		});
		*/
		
		$(".nav .header-bg", target).click(function(e) {
			window.location = $(this).find("a").attr("href");
		});
		
		$(".expandable .tags a").click(function(e) {
			$("#id_t").val($(this).html());
			$("#id_u").val("");
			$("#movement_gallery").submit();
			return false;
		});
		
		var id_o_val = $("#id_o").val();
		$("#id_o").change(function(e) {
			if(id_o_val != $("#id_o").val()) $("#movement_gallery").submit();
		});
		
		var id_u_val = $("#id_u").val();
		$("#id_u").change(function(e) {
			if(id_u_val != $("#id_u").val()) {
				$("#id_t").val("");
				$("#movement_gallery").submit();
			}
		});
		
		var img = $(".photo img",target).hide();
		if(img[0].complete) Module.HomeGallery.transitionIn(target,img);
		else img.load( function() { Module.HomeGallery.transitionIn(target,img) });
		$('.featured .author', target).breakly(5);
	}
}

/**
*
*/
Module.HomeGalleryTest = function() {
	 var o = {
		target:null,
		img:null,
		ul:null,
		slideshow:null,
		target:null,
		interval:null
	}
	
	
}

	
	Module.HomeGalleryNew = function() {
		
	}
	Module.HomeGalleryNew.prototype.init = function() {
		
	}
/**
 *
 */
Module.HomeGallery = {
	o: {
		target:null,
		img:null,
		ul:null,
		slideshow:null,
		target:null,
		interval:null
	},
	
	init:function(target) {
		var self = this; 
		
		self.o = {}; self.o.target = target; target=null; // init
		self.o.target.bind('remove',function() { self.destroy(); });
		Device.log($(".photo img",target));
		self.o.img = $(".photo img",target).hide();	// 1. Transition in the featured photo		
		if(self.o.img[0].complete) Module.HomeGallery.transitionIn(this.o.target,this.o.img);
		else self.o.img.load( function() { Module.HomeGallery.transitionIn(self.o.target,self.o.img) });
		
		self.o.ul = $(".thumbs ul",self.o.target);
		Module.traydress($("li",self.o.ul)); // add traydress rollover
		Module.append_empty_gallery($("li",self.o.ul),6); // fill empty parts of this list
		Module.transition_image($("img",self.o.ul), Module.GalleryRelated.transitionIn); // resize and transition images
		
		
		if($(".extend a",target).attr("href")) { // timer operated, auto-paginate through images if visible and extender exists
			self.o.interval = window.setInterval(function() { 
				if(Module.is_visible(self.o.ul)) Module.HomeGallery.load_next($(self.o.target.selector), self.o.ul);
			},10000);
		}
	},
	
	/* destroy the HomeGallery object */
	destroy:function() {
		if(this.o.slideshow) this.o.slideshow.destroy();
		window.clearInterval(this.o.interval);
		this.o = null;
	},
	
	load_next:function(target, ul) {
		var url = $(".extend a",target).attr("href");
		$.get(url, function(data) {
			Device.log($(".extend a",target).attr("href") + ' // load next');
			Device.log(data);
			var assets = data.response.asset.object_list;
			var page_data = data.response.asset.page_data;
			
			var next_page = (parseInt(page_data.current_page) + 1 ); // update anchor
				next_page = (next_page > parseInt(page_data.page_count)) ? 1 : next_page; // loop back to page 1
			Module.update_anchor_value('page', $(".extend a", target),next_page);
			
			var len = $("img",ul).length;
			$("img",ul).each(function(index,value) {
				$(this).delay(100* (len-index)).fadeOut(500, function() {
					if(len-1 == index) { // last index
						ul.empty();
						for(var i = 0; i < assets.length; i++) {
							var li = $("<li/>").appendTo(ul).addClass("thumb");
							$("<img/>").appendTo(li).attr("src",assets[i].thumb).wrap('<a title='+assets[i].name+'"" href="/en/movement/'+ assets[i].id+'"/>');
							$("<span/>").appendTo(li).html(assets[i].name).addClass("title");
							$("<span/>").appendTo(li).html("by: " + assets[i].user.username).addClass("artist");
						}
						Module.traydress($("li",ul));
						Module.append_empty_gallery($("li",ul),6);
						Module.transition_image($("img",ul), Module.GalleryRelated.transitionIn); // resize and transition images in
					}
				}); // reverse fadeout
			});
		});
	},
	
	transitionIn:function(target,img) {
		var self = this;
		var handle = $(".handle",target);
		var photo = $(".featured .photo",target);
		var ro = (450/375); // (photo.height() > 0) ? (photo.width()/photo.height()) :  (450/375); //
		var rp = (img.width()/img.height())
		if(rp < ro) img.css("width",450); // scale to width and height will crop  
		else img.css("height",375);
		handle.width(img.width()).height(img.height());
		img.delay(500).fadeIn(500,function(){ // user can  move the image to see the whole thing
			if(self.o.slideshow) self.o.slideshow.destroy();
			Device.log("Making slideshow: " + target.attr("id")+ '-slideshow');
			self.o.slideshow = new Dragdealer(target.attr("id")+ '-slideshow', {
				steps: 1,
				loose: true,
				speed: 20,
				slide :true
			});
		});
	}
}

/**
 *
 */
Module.GalleryRelated = {
	
	init:function(target) {
		var ul = $(".thumbs ul",target);
		Module.traydress($("li",ul)); // add traydress rollover
		Module.append_empty_gallery($("li",ul),8); // fill empty parts of this list
		Module.transition_image($("img",ul), this.transitionIn); // resize and transition images
		Module.pagination(target,"asset",this.template);
	},
	
	template:function(target, assets) {
		var ul = $("<ul/>").appendTo($(".thumbs",target));
		for(var i = 0; i < assets.length; i++) {
			var li = $("<li/>").appendTo(ul).addClass("thumb");
			$("<img/>").appendTo(li).attr("src",assets[i].thumb).wrap('<a title='+assets[i].name+'"" href="/en/movement/'+ assets[i].id+'"/>');
			$("<span/>").appendTo(li).html(assets[i].name).addClass("title");
			$("<span/>").appendTo(li).html("by: " + assets[i].user.username).addClass("artist");
		}
		Module.traydress($("li",ul));
		Module.append_empty_gallery($("li",ul),8);
		Module.transition_image($("img",ul), Module.GalleryRelated.transitionIn); // resize and transition images in
		Page.reset();
	},
	
	transitionIn:function(img,index) {	// process runs after image is loaded, should help the processor out a bit?
		var style = {width:92, height:111}; // hard coded because reading off stylesheet doesnt work...
		var ro = (style.width/style.height); // orig ratio
		var rp = (img.width()/img.height())
		if(rp < ro) img.css("width",style.width); // scale to width and height will crop  
		else img.css("height",style.height);
		img.css({"left":(style.width-img.width())/2, "top":(style.height-img.height())/2}); // center the result
		img.delay(index*75).fadeIn(600);
	}
}

/**
 *
 */
Module.GalleryDetail = {	
	init:function(target) {
		
		// 1. Transition in the main image
		var img = $(".content .photo img.flow",target);
		img.hide();
		if(img[0].complete) this.transitionIn(target,img);
		else img.load( function() { Module.GalleryDetail.transitionIn(target,img) });
		
		// 2. Toggle expandable interactive pieces
		Module.toggle(target);// Toggle expandable interactive pieces
		Module.flag(target);	
		
		$('h1', target).breakly(5);

		// 3. favorites form confirmation
		$(".favorite li.toggle-confirm",target).click(function(e) {
			var t = $(this);
			$(".action-menu .favorite-loader",target).fadeIn(500);
			$.get($(this).find("a").attr("href"), function(data) {
				var count = $(".action-menu .favorite-count span");
				count.html( parseInt(count.html())+1);
				t.siblings().css("margin-top","0").find("a").attr("href","#").html("Added to Favorites!"); // clear click
				t.remove();
				$(".action-menu .favorite-loader",target).fadeOut(500);
			});
			return false;
		});
		
		if($("#flickr_api").length) { // make sure you have the right license for flickr images
			Flickr.quick_load($("#flickr_api"), function(data) { // flickr.photos.getInfo get license info
				if(data && data.photo) {
					var url = '/en/feeds.json?license={"per_page":"1","page":"1","flickr":"'+data.photo.license+'"}';
					$.get(url,function(data){
						if(data && data.response && data.response.license) {
								var license = data.response.license.object_list[0];
								$("ul.license li").empty().append('<a href="'+license.url+'" target="_offsite" title="'+license.name+'"><img src="'+license.image+'" alt="'+license.name+'"></a>');
						}// else error
					});
				}// else error
			});
		}
		
	},
	
	transitionIn:function(target,img) {
		var info = $(".content > .info",target);
		var content = $("> .content",target);
		var loader = $(".content .loader-icon",target);
		var photo = $(".content .photo",target);
		
		content.width(img.width() + info.outerWidth());
		Page.resize(true); //lock width since we're animating
		content.width(info.outerWidth()).animate({"width":img.width() + info.outerWidth()},{duration:500, easing:"easeOutExpo", complete:function(e) {}}) // animate IN the picture
		photo.css({"width":0}).animate({"width":img.width()},{duration:500, easing:"easeOutExpo", complete:function(e) {
			img.fadeIn(500);
			loader.fadeOut(500); // fade out the loader
			Page.resize(false); //unlock width
		}});
	}
}

Module.Comments = {
	
	row:"row1",
	submitting:false,
	
	init:function( target ){
		/* pagination */
		Module.pagination(target,"comment",this.template);
		Module.toggle(target, $(".action a.toggle",target).parent());		
		this.submit_comment(target);
		this.config_flag(target,  "Removed!", "Thank You!");
	},
	
	config_flag:function(target, onCompleteStatus1, onCompleteStatus2) {
		var expandable = $(".expandable.flag",target);
		$(".flag a.toggle",target).live('click', function(e) {
			if(!Module.Comments.submitting) {
				var isHiding = ( expandable.css("display") == "none");
				$(".expandable").hide();// hide all
				if(isHiding || !$(".expandable",$(this).parent()).length ) {
					expandable.show();
					expandable.appendTo($(this).parent());
					expandable.find(".toggle-confirm a").attr("href",$(this).attr("href"));
					$(".toggle-confirm", expandable).show();
				}
			}
			return false;
		});
		
		
		$(".toggle-confirm", expandable).click(function(e) {
			var a = $(this).find("a");
			if(!Module.Comments.submitting) {
				var orig = a.html();
				Module.Comments.submitting = true;
				a.html("Submitting....");
				$.get(a.attr("href"),function(data) {					
					if($(".flag a.toggle",target).hasClass("closeModal")) {
						a.html(onCompleteStatus1);
						expandable.parents("li").fadeOut(500,function(e) {
							a.html(orig);
							expandable.hide().appendTo($(".content",target));
							$(this).remove();
							Module.Comments.submitting = false;
						});
					}else {
						a.html(onCompleteStatus2);
						expandable.parents(".flag").find("a.toggle").hide();
						expandable.delay(500).fadeOut(500,function(e) {
							a.html(orig);
							Module.Comments.submitting = false;
						});
					}
				});
			}
			return false;
		});
	},
	
	submit_comment:function(target) {
		/* expandable submit forms */
		
		$(".toggle-confirm",target).click(function(e) {  $(this).parents("form").submit();  return false;});
		$("form#comment",target).submit(function(e) {
			var a = $(".toggle-confirm a",$(this));
			var orig = a.html();
			a.html("Submitting...");
			$.post($(this).attr("action"), $(this).serialize(), function(data) {
				location.reload();
			});
			return false;
		});
	},
	
	/* template used to load new comments using ajax */
	template:function(target, comments) {
		var expandable = $(".expandable.flag",target);
		var ul = $("<ul/>").appendTo($(".content",target));
		for(var i = 0; i < comments.length; i++) {
			var name = comments[i].user.first_name + " " + comments[i].user.last_name.charAt(0) + ".";
			var avatar = comments[i].user.avatar; avatar = (avatar) ? avatar : "http://c0026181.cdn1.cloudfiles.rackspacecloud.com/uploads/avatars/default_avatar.png";
			var li = $("<li/>").appendTo(ul).addClass(Module.Comments.row);
			$("<div/>").appendTo(li).addClass("avatar").append( ((avatar) ? '<a href="/en/movement/'+ comments[i].user.id + '" title="'+name+'"><img src="'+avatar+'"/></a>' : ''));
			$("<div/>").appendTo(li).addClass("account").html(
				'<p><a href="/en/movement/'+ comments[i].user.id + '" title="'+name+'">'+name+'</a></p>'
				+ '<p class="date">'+ comments[i].created + '</p>'
				+ '<p>'+ comments[i].body + '</p>'
			);
			/* add the delete x flag buttons */
			if(expandable.length) {
				if(expandable.find(".delete").length){
					$('<div class="flag"/>').appendTo(li).append('<a href="/en/social/remove/comment/'+comments[i].id+'?ajax" class="toggle icons closeModal" title="Delete Comment"></a>');
				}else {
					$('<div class="flag"/>').appendTo(li).append('<a href="/en/social/flag/comment/'+comments[i].id+'?ajax" class="toggle" title="Flag Comment"><img src="/media/img/icons/flag.png"/></a>');
				}
			}
		}
		var nextRow = (Module.Comments.row=="row1") ? "row2" : "row1";
		$("li:nth-child(2n)",ul).addClass(nextRow).removeClass(Module.Comments.row);
		Module.Comments.row = nextRow;
	}
}

/**
 *
 */
Module.TwitterComments = {
	target:null,
	row:"row2",
	o:{
		page:null,
		user:null,
		count:3
	},
	
	init:function(target, userName) {
		this.target = target;
		//twttr.anywhere(function (T) { T("#tweet").tweetBox({ height: 90, width: 240, counter:1, defaultContent: "#polaroid", label:""}); });
		Module.toggle(target, $("a.toggle",target).parent(),function() {
			if(twttr && typeof(twttr.anywhere) != 'undefined') twttr.anywhere.config();
			var interval = window.setInterval(function(){
				if($("#tweet iframe").length) { // remove the loader icons once loaded
					$("#tweet .loader-icon").fadeOut(500);
					window.clearInterval(interval);
					$("#tweet iframe").css({"width":"100%","height":"170px"});
				}
			}, 200); 
		});
		
		// NEEDS TO POST, NOT GET, SHOULD SEND AUTH TOKENS AND SECRET WITH POST
		Module.Comments.config_flag(target, "ReTweeted!", "ReTweeted!");
		
		$(".expandable ul.comment .toggle-confirm",target).click(function(e) { 
			$(this).parents("form#twitter_form").submit(); 
		});

		$("form#twitter_form",target).submit(function(e) {
			var a = $(".toggle-confirm a",$(this));
			var orig = a.html();
			a.html("Submitting...");
			return false;
		});
		
		if(userName) {
			this.load(userName,3,1, function() {
				$(".extend",target).click(function(e) {
					Module.TwitterComments.load(Module.TwitterComments.o.user, 4, Module.TwitterComments.o.page+1);
				});
			});
		}
	},
	
	
	load:function(user, count, page, onComplete) {
		this.o = {user:user, count:count,page:page};
		$(".loader-icon",this.target).show();
		var url = "https://api.twitter.com/1/statuses/user_timeline/"+user+".json?include_rts=true&callback=Module.TwitterComments.template&page="+page+"&count="+count;		
		$.getScript(url, function() {
			$(".loader-icon",Module.TwitterComments.target).fadeOut(500);
			if(onComplete) onComplete();
		});
	},

	template:function(twitters) {
		var statusHTML = [];		
		for (var i=0; i<twitters.length; i++){
			this.row = (this.row=="row1") ? "row2" : "row1";
			var username = twitters[i].user.screen_name;
			var status = twitters[i].text.replace(/((https?|s?ftp|ssh)\:\/\/[^"\s\<\>]*[^.,;'">\:\s\<\>\)\]\!])/g, function(url) { return '<a href="'+url+'">'+url+'</a>'; }).replace(/\B@([_a-z0-9]+)/ig,  function(reply) { return  reply.charAt(0)+'<a href="http://twitter.com/'+reply.substring(1)+'">'+reply.substring(1)+'</a>'; });
			statusHTML.push(( '<li class="'+this.row+'">'
				+ '<div class="avatar"><img src="'+ twitters[i].user.profile_image_url + '"/></div>'
				+ '<div class="account">'
					+ '<p><a href="http://twitter.com/'+username+'" target="_twitter">'+username+'</a></p>'
					+ '<p><a href="http://twitter.com/'+username+'/statuses/'+twitters[i].id+'" class="date" target="_twitter">'+Module.format_time(twitters[i].created_at)+'</a></p>'
					+ '<span>'+status+'</span>'
				+ '</div>'
				+ (($(".expandable.flag",Module.TwitterComments.target).length) ? '<div class="flag"><a href="https://api.twitter.com/1/statuses/retweet/'+twitters[i].id+'.json" class="toggle"><img src="/media/img/icons/retweet.png"/></a></div>' : '')
			+ '</li>'));
			
			// add RT <a href="http://twitter.com/'+username+'" target="_twitter"> on RTs, 
		}
		this.row = (this.row=="row1") ? "row2" : "row1";
		if(statusHTML.length) {
			var ul = ($("ul.twitter_list",this.target).length) ? $("ul.twitter_list",this.target) : $("<ul>").appendTo($(".content",this.target))
			ul.append(statusHTML.join('')).removeClass("twitter_list"); // attatch 
			$(".extend",this.target).appendTo($(".content",this.target)); // move extend grid to the end of the list
			Page.reset();
		}
		if(statusHTML.length < this.o.count) { 
			$(".extend",this.target).fadeOut(500, function() { Page.reset(); }); 
		}
	}
}
/**
 *
 */
Module.ProfileDetail = {
	target:null,
	
	init:function(target, userName) {
		this.target = target;
		
		$('span.author', target).breakly(5);
		
		Module.toggle(target);// Toggle expandable interactive pieces
		Module.flag(target);
		
		var img = $(".photo img",target).hide();
		if(img[0].complete) Module.HomeGallery.transitionIn(target,img);
		else img.load( function() { Module.HomeGallery.transitionIn(target,img) });
		
		if(userName) {
			this.load(userName,1,1);
		}
	},
	
	load:function(user, count, page) {
		$(".loader-icon",this.target).show();
		var url = "https://api.twitter.com/1/statuses/user_timeline/"+user+".json?include_rts=true&callback=Module.ProfileDetail.template&page="+page+"&count="+count;		
		$.getScript(url, function() {
			$(".loader-icon",Module.ProfileDetail.target).fadeOut(500);
		});
	},
	
	template:function(twitters) {
		var statusHTML = [];		
		for (var i=0; i<twitters.length; i++){
			this.row = (this.row=="row1") ? "row2" : "row1";
			var username = twitters[i].user.screen_name;
			var status = twitters[i].text.replace(/((https?|s?ftp|ssh)\:\/\/[^"\s\<\>]*[^.,;'">\:\s\<\>\)\]\!])/g, function(url) { return '<a href="'+url+'">'+url+'</a>'; }).replace(/\B@([_a-z0-9]+)/ig,  function(reply) { return  reply.charAt(0)+'<a href="http://twitter.com/'+reply.substring(1)+'">'+reply.substring(1)+'</a>'; });
			statusHTML.push('<li><div class="tweet"><span>'+status+'</span><div class="date"><a style="font-size:85%" href="http://twitter.com/'+username+'/statuses/'+twitters[i].id+'">'+Module.format_time(twitters[i].created_at)+'</a></div></div></li>');
		}
		if(statusHTML.length) {
			var ul = ($("ul.twitter_list",this.target).length) ? $("ul.twitter_list",this.target) : $("<ul>").appendTo($(".content",this.target))
			ul.append(statusHTML.join('')).removeClass("twitter_list"); // attatch 
		}
	}
}

/**
 * Dependencies: 	flickr.js 
 *					templates/modules/Profile Settings.html
 * Example			: Profile Settings.html >>   Module.ProfileSettings.init($("#module-28"));
 */
Module.ProfileSettings = {
	
	init: function(target) {
		var nav = $(".controlPanelNav ul li",target);
		var panel = $(".panel",target);
		var subnav = $('#panel-submit-image .content .connectionList .connection', target);
		var subpanel = $(".sub-panel",target);
		var curpanel = null;
		var cursubpanel = null;
		
		///////////////// Primary Nav
		nav.click(function(e) {					// click primary nav
			if($(this).hasClass("selected")) return;
			
			subnav.removeClass("selected");
			subpanel.removeClass("on").find(".circle").removeClass("dim"); // reset the header circle			
			target.find(".circle").removeClass("dim"); // reset panel headers
		
			panel.removeClass("on"); // reset all panels (reset interiors)
			$(this).parent().children().removeClass("selected"); // reset all menu items
			$(this).addClass("selected"); // set this menu item
			curpanel = $("#panel-" + $(this).attr("id")).addClass("on"); // locate associated panel and activate it
			Page.resize();
			Form.init();
			return false;
		});
		
		/* zoom for traydress on flickr imported images. commented out for issues with Confirm context. see Flickr.js 48 to add photo-details for traydress rollover
		$(".zoom",target).live('mouseover',function(e) {
			Module.traydress_mouseover(e,$(this).parents(".thumb"));
		});
		*/
		
		$("#panel-submit-image-import-flickr .paginator select").change(function(e) {
			$('#panel-submit-image-import-flickr #page').val($(this).val());
			Flickr.load($("#panel-submit-image-import-flickr"));
		});
		
		//////////////// My Connections Nav
		$("#panel-connections .connection").click(function(e) {	// clicked connection in My Connections
			if($(this).hasClass("enabled")) return;
		});
		
		
		$("#profile_form").submit(function(data) {
			var form = $(this);
			var loader = $(".loader-icon",form);
			
			loader.find("span").html("Sending....");
			loader.fadeIn(500);
			
			// post form
			$.post($("#profile_form").attr("action"), $("#profile_form").serialize(), function(response) {
				if(!Form.error(response, form )) { 
					loader.find("span").html("Success!");
					loader.delay(1000).fadeOut(500);
				}else {
					loader.find("span").html("Errors!");
					loader.delay(1000).fadeOut(500);
				}
			});
			return false;
			
		});
		
		var import_in_progress = false;
		//////////////// Import to Flickr Confirm Panel/ Completes the import
		$("#panel-submit-image-import-confirm form").submit(function(e) {
			if(import_in_progress) return false;
			import_in_progress = true;
			var submit = $(".submit",$(this)).val("Importing...");
			$.post($(this).attr("action"),$(this).serialize(), function(response) {
				submit.val("Import Complete");
				var count = 3;
				var span = $("#panel-submit-image-import-confirm form").find(".results ul").empty().append("<li><p>Images successfully imported. Refreshing in <span>"+count+"</span>...</p></li>").find("span");
				var interval = window.setInterval(function() {
					span.html(count);
					count--;
					if(count<=0)location.reload();
				},1000);
			});
			return false;
		});
		
		///////////////// Submit Image Panel
		subnav.click(function(e) {				// click secondary nav (only Submit image has secondary nav and secondary panels)
			if($(this).hasClass("selected")) return;
			
			subpanel.find(".circle").removeClass("dim");
			
			subpanel.removeClass("on"); // reset all subpanels TODO: reset interiors
			subnav.removeClass("selected");	// reset sub-nav
			
			$(this).addClass("selected"); // turn on this menu item
			curpanel.find(".circle").addClass("dim");
			
			cursubpanel = $("#" + curpanel.attr('id') + "-" + $(this).attr('id')).addClass("on"); // turn on sub-panel
			
			switch(curpanel.attr('id')) {
				case 'panel-submit-image':
					switch(cursubpanel.attr('id')) {
						case 'panel-submit-image-upload':
							$("#id_file", cursubpanel).change(function(e){	// change the input file 
								$("#id_file_name",cursubpanel).val($(this).val());
							});
							break;
						case 'panel-submit-image-import-flickr':
							Flickr.load(cursubpanel); // load flickr account / media/js/Flickr.js
							break;
					}
					break;
			}						
			Page.resize();
			Form.init();
			return;
		});
		
		// open to specific page
		switch(Device.querystring("panel")) {
			case 'upload':
				setTimeout(function() { $(".controlPanelNav #submit-image",target).click(); }, 500);
				setTimeout(function() { $(".connectionList #upload",target).click(); }, 1500);
				break;
		}
		//////////////////// FEATURED IMAGE
		this.featured_image_click(target,curpanel);
		
		// setup featured paginator:
		var opts='';
		for(var i = 1; i <= parseInt($("input#featured_page_count").val()); i++) {
			opts += ('<option value="'+i+'">'+i+'</option>');
		}
		$("form#featured_paginator select#page",target).empty().append($(opts)).change(function(e) {
			var form = $("form#featured_paginator",target);
			var fields = form.serializeArray();
			var json = {};
			for (i in fields) { json[fields[i].name] = fields[i].value }
			var url = form.attr("action") + "?asset=" + unescape($.toJSON(json));
			$.get(url, function(data) {
				if(data) {
					var list = data.response["asset"].object_list;
					Module.ProfileSettings.featured_template(target,list);
					Module.ProfileSettings.featured_image_click(target,curpanel);
				}
			});
		});
	},
	
	featured_image_click:function(target,curpanel) {
		//////////////// Featured Image Nav
		$("#panel-featured-image li",target).click(function(e) {		// clicked image in featured image
			if($(this).hasClass("confirm")) {
				//$(this).removeClass("confirm"); // remove this as the featured image
			}else { // add confirm and send to POST
				$(this).parent().children().removeClass("confirm");
				$(this).addClass("confirm");
				$("#profile_form #id_featured_asset").val($(this).attr('id'));
				var img = $(this);
				$(".loader-icon",curpanel).fadeIn("500","easeInOutExpo");
				$.post($("#profile_form").attr("action"), $("#profile_form").serialize(), function(response) {
					// DATA SENT SUCCESSFULLY ... CHANGE THE IMAGE
					$("section .profile-detail div.featured").removeClass("hidden").find("img").attr({"src":img.find("img").attr("alt"),"alt":img.find("img").attr("title")}); // add full size image
					$("section .profile-detail div.featured").find("a").attr({"title":img.find("img").attr("title"),"href":img.find("#get_absolute_url").html()})
					$("section .profile-detail div.featured").find(".author").html(img.find("img").attr("title").substr(0,45)).breakly(5);
					$(".loader-icon",curpanel).fadeOut("500","easeInOutExpo");
				});				
			}
			return false;
		});	
	},
	
	featured_template:function(target, assets) {
		var ul = $("<ul/>").appendTo($("#panel-featured-image .thumbs",target).empty());
		for(var i = 0; i < assets.length; i++) {
			var li = $('<li id="'+assets[i].id+'"/>').appendTo(ul).addClass("thumb border");
			$("<img/>").appendTo(li).attr({"src":assets[i].thumb, "alt":assets[i].asset, "title":assets[i].name});
			$('<div class="confirm"><span>Featured</span></div>').appendTo(li);
			$('<div class="hidden" id="data"><ul><li id="get_absolute_url">/movement/'+ assets[i].id + '</li></ul></div>').appendTo(li);
			if(assets[i].user.featured_asset.id === assets[i].id) li.addClass("confirm");
		}
		Module.transition_image($("img",ul), Module.GalleryRelated.transitionIn); // resize and transition images in
	}
}

/**
 * Privacy Policy Module
 *
 */
Module.PrivacyPolicy = {	
	init:function(target) {
		//Module.autocolumn($("div.answers",target));
		Module.inlinemenu(target);
	}
}

Module.SiteMap = { 
	init:function(target) {
		//Device.log($("div.sitemapBox",target));
		$("#answerList").columnize({balanced: false, height:400, minHeight:400,dontsplit:".dontsplit, .back"});
		//Module.autocolumn($("div.sitemapBox",target));
	}
}

/**
 * FAQ Module
 *
 */
Module.FAQ = {	
	init:function(target) {
		Module.autocolumn($("div.answers",target));
		Module.inlinemenu(target);
	}
}


Module.ProductDetail = {
	
	init: function(target) {
		$(".content.featured-product .product-detail-overview",target).click(function(e) {
			window.location = $(this).find("a").attr("href");
			return false;
		});
		
		var slideshow = null;
		if( $(".handle ul li",target).length > 1) {  // build slideshow
			$(".handle",target).width( $(".handle ul li",target).length * 540 );
			$(document).ready(function() {
					slideshow = new Dragdealer(target.attr("id")+'-slideshow', {
					steps: $(".handle ul li",target).length,
					loose: true,
					speed: 20,
					slide :true,
					animationComplete: function(obj)
					{
						var step = this.currentStep()[0];
						$(".slide-show-controls ul li",target).removeClass("highlight");
						$(".slide-show-controls ul li:nth-child("+(step+1)+")",target).addClass("highlight");
					}
				});
			});
		}
		// slideshow controls
		$(".slide-show-controls ul li",target).click(function(e) {
			$(".slide-show-controls ul li",target).removeClass("highlight");
			slideshow.setStep($(this).index());
			$(this).addClass("highlight");
		});
		
		Module.toggle(target);// Toggle expandable interactive pieces
		// 3. favorites form confirmation
		$(".favorite li.toggle-confirm",target).click(function(e) {
			var t = $(this);
			$(".action-menu .favorite-loader",target).fadeIn(500);
			$.get($(this).find("a").attr("href"), function(data) {
				t.siblings().css("margin-top","0").find("a").attr("href","#").html("Added to Wislist!"); // clear click
				t.remove();
				$(".action-menu .favorite-loader",target).fadeOut(500);
			});
			return false;
		});
		
		// slide to color picture
		$(".color-options li",target).click(function(e) {
			$(".slide-show-controls ul li",target).removeClass("highlight");
			var index = $(".slide-show-controls ul #" + $(this).attr("id"),target).addClass("highlight").index();
			slideshow.setStep(index);
			return false;
		});
		
		// auto scroll to selected color
		var c = Device.querystring("color");
		if(c) {
			var index = $(".slide-show-controls ul #photo_"+c,target).addClass("highlight").index()
			if(index)  slideshow.setStep(index);
		}
	}
}

Module.ProductCategories = {
	init: function(target) {
		var slideshow = null;
		$(document).ready(function() {
			var mask = $("#scroll-mask",target);
			var content = $("#scroll-content",target);
			slideshow = new Dragdealer(target.attr('id') + '-scroller', {
				horizontal: false,
				vertical: true,
				speed:20,
				mask:mask,
				content:content,
				yPrecision: content.outerHeight(),
				animationCallback: function(x, y) { 
					//mask.scrollTo(( y*(content.outerHeight()-mask.outerHeight())),0,{axis:'y'}); 
					mask.scrollTop(( y*(content.outerHeight()-mask.outerHeight())),0,{axis:'y'});
				}
			});
			
			$(window).resize(function(event) { 
				$(".handle",target).height( (mask.height()/content.height())* $(".dragdealer",target).height() );
			});			
		});
	}
}

Module.ProductRelated = {
	
	init: function(target) {		
		Module.pagination(target,"product",this.template);
		
		var expandable = $(".expandable",target);
		$(".toggle",target).live('click', function(e) {
			
			var isHiding = ( expandable.css("display") == "none");
			$(".expandable").hide();// hide all
			$(".toggle").removeClass("border");
			
			
			if(isHiding || !$(".expandable",$(this).parent()).length ) {
				$(this).addClass("border");
				expandable.show()
				expandable.appendTo($(this).parent());
				expandable.find(".toggle-confirm a").attr("href",$(this).attr("href"));
			}
			return false;
		});
				
		$(".toggle-cancel",expandable).click(function(e) {
			$(".toggle",target).removeClass("border");
			$(this).parents(".expandable").hide();
			return false;
		});
		// Confirm removal from wishlist
		$(".toggle-confirm",expandable).click(function(e) {
			var t = $(this);
			$.get(t.find("a").attr("href"), function(data) {
				location.reload();
			});
			return false;
		});
	},
	
	template:function(target, products) {
		var ul = $("<ul/>").appendTo($(".content",target)).addClass("extra");
		for(var i = 0; i < products.length; i++) {
			var li = $("<li/>").appendTo(ul).addClass("product");
			var html = '<a href="'+((products[i].featured) ? products[i].absolute_url : products[i].more_info_url) +'" title="'+products[i].name+'"><div class="table">'
						+ 	'<div class="product-img center">'
						+ 		'<span></span>'
						+ 		'<img src="'+products[i].preview+'" alt="'+products[i].name+'">'
						+ 		'<p>'+products[i].name+'</p>'
						+ 	'</div>'
						+ 	(($(".extendable",target)) ? '<a href="/en/social/remove/wishlist/' + products[i].id + '?ajax" class="toggle icons closeModal" title="Remove from Wishlist" href="#">Remove</a>' : '')
					+ '</div></a>';
			li.html(html);
			$("<img/>").appendTo(li);
		}
	}
}

Module.MultiColumnFlow = {
	init:function(){
		$("#answerList").columnize({balanced: false, height:440, minHeight:440,dontsplit:".dontsplit, .back"});
	}
}

Module.ProfileFavorites = {
	init:function(target, disable_trydress) {
		var expandable = $(".expandable",target);
		$(".toggle.closeModal",target).live('click', function(e) {
			var isHiding = ( expandable.css("display") == "none");
			$(".expandable").hide();// hide all
			$(".closeModal").removeClass("border");
			if(isHiding || !$(".expandable",$(this).parent()).length ) {
				$(this).addClass("border");
				expandable.show();
				expandable.appendTo($(this).parent());
				expandable.find(".toggle-confirm a").attr("href",$(this).attr("href"));
			}
			return false;
		});
				
		$(".toggle-cancel",expandable).click(function(e) {
			$(".toggle",target).removeClass("border");
			$(this).parents(".expandable").hide();
		});
		// Confirm removal from wishlist
		$(".toggle-confirm",expandable).click(function(e) {
			var t = $(this);
			$.get(t.find("a").attr("href"), function(data) {
				location.reload();
			});
			return false;
		});
		
		$(".zoom",target).live('mouseover',function(e) {
			Module.traydress_mouseover(e,$(this).parents(".thumb"));
		});
		
		var ul = $(".thumbs > ul",target);
		
		if(!disable_trydress) Module.traydress($("li",ul)); // add traydress rollover
		Module.append_empty_gallery($("li",ul),8); // fill empty parts of this list
		Module.transition_image($("img",ul), Module.GalleryRelated.transitionIn); // resize and transition images
		Module.pagination(target,"asset",this.template);
	},
	
	template:function(target, assets) {
		var ul = $("<ul/>").appendTo($(".thumbs",target));
		for(var i = 0; i < assets.length; i++) {
			var li = $("<li/>").appendTo(ul).addClass("thumb");
			$("<img/>").appendTo(li).attr("src",assets[i].thumb).wrap('<a title='+assets[i].name+'"" href="/en/movement/'+ assets[i].id+'"/>');
			$("<span/>").appendTo(li).html(assets[i].name).addClass("title");
			$("<span/>").appendTo(li).html("by: " + assets[i].user.username).addClass("artist");
			html = '<div class="removable"><a href="#" class="toggle icons zoom" title="Zoom" href="#">Zoom</a><a href="/en/social/remove/favorite/'+assets[i].id + '?ajax" class="toggle icons closeModal" title="Remove from Favorites" href="#">Remove</a></div>';
			li.append(html);
		}
	
		Module.append_empty_gallery($("li",ul),8);
		Module.transition_image($("img",ul), Module.GalleryRelated.transitionIn); // resize and transition images in
		Page.reset();
	}
}
Module.ProductsList = {
	init:function(target) {
		Module.columnize(target);
	}
}

Module.Tabs = {
	
	init:function(target, scrollers) {
		
		$(scrollers).each(function(index) {
			var id = scrollers[index];
			var mask = $("#"+id +"-scroll-mask",target);
			var content = $("#"+id +"-scroll-content",target);
			mask.parent().bind('show', function(event, ui) {
				if(!this.slideshow) {
					this.slideshow = new Dragdealer(id +'-scroller', {
						horizontal: false,
						vertical: true,
						yPrecision: content.outerHeight(),
						mask:mask,
						content:content,
						animationCallback: function(x, y) { 
							mask.scrollTo(( y*(content.outerHeight()-mask.outerHeight())),0,{axis:'y'}); 
						}
					});
					if(Device.can_touch) mask.jScrollTouch(false,this.slideshow);
				}
			});
			
		});

		$(".content .tab-content > div",target).removeClass("hidden");
		$(".content",target).tabs(
		{ 
			fx: { opacity: 'toggle' },
			show:function(event, ui) {
				$(ui.panel).trigger("show",[event,ui]);
			}
		}).tabs('rotate', 5000);
	}
}

Module.Blog = {
	init:function(target) {
		var li = $("li.entry",target);
		for(var i = li.length; i < 3; i++) {
			$("<li/>").appendTo(li.parent()).addClass("entry empty-content");
		}
	}
}

Module.Search = {
	
	init:function(target) {
		$("a.header",target).breakly(5); // search title
	}
	
}
/**
* 	Example use: Flickr.load($("#target"),Flickr.associate); //
* 	Not very customizable unfortunately, the main var to note is load.url
*	Author - Christian Harden / RED Interactive / 
*/
var Flickr = {
	
	quick_load:function (form, onComplete) {
		var url = "http://api.flickr.com/services/rest/?" +  unescape(form.serialize());
		$.getJSON(url, function(data) {
			if(onComplete && typeof(onComplete)=="function") onComplete(data);
		});
	},
	
	/*
	* Load images from flickr
	* @param target		- jquery element to inject with Flickr images
	*/
	load: function(target) {
		var form = $("#flickr_api",target);
		var url = "http://api.flickr.com/services/rest/?" +  unescape(form.serialize());
		var results = ($(".results",target).length ) ? $(".results",target) : $("<ul>").appendTo(target).addClass("results");
		var icon = $(".loader-icon",target).show();
		var stored_photos = $("#stored_photos",target);
		var pending_photos = $("#pending_photos",target); // reset
		
		var confirm_panel = $("#panel-submit-image-import-confirm");
		if($(".results ul li",confirm_panel).length) confirm_panel.addClass("on");
		
		$.getJSON(url, function(data) {
			results.children().unbind();
			results.empty(); // reset
			
			icon.fadeOut(500,"easeInOutExpo");
			
			$.each(data.photos.photo, function(i,item) {
				var img = $('<li id="photo_'+item.id + '" class="thumb"><div><img src="'+ item.url_s + '" title="'+item.title+'"></div></li>').appendTo(results).addClass("border");
				if(stored_photos.hasClass(item.id)) {
					img.addClass("selected");
					$('<div>').addClass("selected").appendTo(img).append("<span>Imported</span>");
				}else if(pending_photos.hasClass(item.id)) {
					img.addClass("confirm"); // add confirm ui
					$('<div>').addClass("confirm").appendTo(img).append("<span>Please Confirm!</span>");	
				}else {
					img.bind("click",function(e) {  Flickr.associate($(this),item, target);  });
					//img.append($('<span class="title">Title</span><span class="artist">Artist</span><div class="removable"><a href="#" title="Zoom" class="toggle icons zoom">Zoom</a></div>'));
				}
				//resize
			});
			
			Module.transition_image($("img",results), Module.GalleryRelated.transitionIn); 
			Flickr.paginator(target,data.photos,form);
		});
	},
	
	paginator: function(target, data, form) {
		var select = $(".paginator select",target);
		var curpage = parseInt(data.page);
		var total = parseInt(data.pages);
		var perpage = parseInt(data.perpage);
		
		if(total > 1) {
			select.children().remove();
			for(var n = 1; n <= total; n++) {
				$("<option>").appendTo(select).val(n).html(n).attr("selected",((n == curpage)?"selected":""));
			}
		}else {
			select.parent().addClass("hidden");
		}
	},
	
	/*
	* Associates the Flickr image to Polaroid account (sends to "confirmation" panel)
	*/
	associate: function(target,item, container) {
		
		container.find(".circle").addClass("dim"); // if user reloads (until removed) this item will not be clickable
		var stored_photos = $("#stored_photos",container);
		var pending_photos = $("#pending_photos",container).addClass(item.id);
		
		var confirm_panel = $("#panel-submit-image-import-confirm").addClass("on"); // open confirm panels
		var clone = target.clone().appendTo($("#panel-submit-image-import-confirm ul"));	// clone li		
		clone.find("img").css({"width":"auto", "height":"70px"});
		clone.removeClass("border");
		
		target.unbind(); // remove click
		target.addClass("confirm"); // add confirm ui
		$('<div>').addClass("confirm").appendTo(target).append("<span>Please Confirm!</span>");						
		$("<span>" + item.title + "</span>").appendTo(clone).breakly(5); // add title
		$("<input type='hidden' name='flickr_img_" + item.id + "' id='flickr_img_" + item.id + "'/>").appendTo(clone).val(unescape($.toJSON(item)));
		$('<a title="Cancel Import" href="#photo_' + item.id + '"></a>').prependTo(clone).click(function(e) {	// cancel img sync
			// cancel import
			var selectable = $($(this).attr("href"),container);
			$(".confirm",selectable).remove(); 
			selectable.removeClass("confirm");
			pending_photos.removeClass(item.id);
			if(clone.parent().children().length <= 1) {
				container.find(".circle").removeClass("dim");
				confirm_panel.removeClass("on");// hide this panel
			}
			selectable.bind("click",function(e) { Flickr.associate(selectable, item, container ); });
			clone.remove();
			return false;
		}); // add remove button
		
		Page.resize();
	}
}
