(function($) {
	//
	// plugin definition
	//
	$.fn.collection = function(action,options) {
 		if(typeof action == "object" && !options){
			options= action;
			action=false;
		}
		 // build main options before element iteration
		var opts = $.extend({}, $.fn.collection.defaults, options);
		var disable=false;
		if(!action) action="init";
		if(action=='disable') {
			action='init';
			disable=true;
		}
		return $(this).each(function() {
			$this = $(this);
			// build element specific options
			var o = $.metadata ? $.extend({}, opts, $(this).metadata()) : opts;
			var $col= $(this);
			//$this.data("image-uploader",o); 
			
			switch(action){
				case "init":
					/*
					var $xb= $(".xk_itm .xblok.new");
					var cn = $xb.metadata().cn;
					if(!cn) cn='';
					$.fn.collection.defaults.addItemFormId= 'frm_xblokADD__'+$xb.metadata().loc+'-'+cn;					
					var $xk= $(".xk_collection");
					cn = $xk.metadata().cn;
					if(!cn) cn='';
					$.fn.collection.defaults.addCollectionFormId= 'frm_xblokADD__'+$xk.metadata().loc+'-'+cn;
					//alert();
					*/
					$col.unbind(".collection");
					$count= $col.find(".count");
					var sz = collections[$col.metadata().colid].sz;
					if(!$count.size()) $col.find(".rok.name span.content").append("<Br />["+sz+" paintings]<br />");
					
					if(disable) return false;
					$col.bind("click.collection",function(e){
							if($(this).hasClass("loaded") && $("#collections").is(".scrollable")){
								return false;
							}
							if(appMode=="EDIT") {
								//if($("#collections").is(".scrollable")) return false;
								//console.dir({e_colClick:e});
								if($(e.target).is("a.edit")){
									return false;
								}
								if($(this).is(".xb_sortable")) return false;
								//console.dir({e_target:e.target});
							}
							//var col_api = $("#collections div.mx_pub").data("scrollable");
							$col = $(this);	
							$col.addClass("loaded").siblings().removeClass("loaded");
							
							
							colid= $col.metadata().colid;
							col = collections[colid];
							colidx = $col.parent().children().index($col[0]);
							
							//col_api.select(colidx,'collection',false);
							$("#collectionName").html("Collection: "+col.collectionName.replace("<br />","&nbsp;"));
							$("#editItems").attr("href",col.href);
							//console.dir({'colidx':colidx,si:col_api.getSelectedIndex()});
							
							
							var myitems = col.items;
							//console.dir({'col':col});
							//console.dir({'myitems':myitems});
							var src='';
							var x=0;
							var temp;
							
							var $new = $("#newItem");
							itm_api.getItems().remove();
							$(".navi").empty();
							var this_itmid=0;
							
							//console.dir({'myitems':myitems});
							for(i in myitems){
								$clone= $new.clone();
								$clone.metadata()['itmid']= myitems[i];
								itm_api.addItem($clone.collectionItem());
								//console.dir({'clone':$clone});
							}
							//console.dir({'items':itm_api.getItems() });
							
							
							//var $frm=$("#"+$.fn.collection.defaults.addItemFormId);
							//console.dir({addForm:$frm});
							//setVal($("select[name$=collectionid]",$frm)[0],colid);
							var tw=itm_api.getSize()*14,w=0;
							w= tw >700 ? tw/2 : tw;
							w= w >700 ? tw/3 : w;
							w= w >700 ? tw/4 : w;
							w= w >700 ? tw/5 : w;
							$("div.navi").css({width:w+'px',margin:'2px auto'});
							
							itm_api.getItems().eq(0).click();
							//console.dir({'itm_api':itm_api});
							
							$("#collections").collectionsScrollable(true);
							return false;
						});							
				break;
				
			}			
		 });
	};
	
	$.fn.collection.defaults= {
		addItemFormId:"",
		addCollectionFormId:""
	};
	
	
	
	$.fn.collectionItem = function(action,options) {
 		if(typeof action == "object" && !options){
			options= action;
			action=false;
		}
		 // build main options before element iteration
		var opts = $.extend({}, $.fn.collectionItem.defaults, options);
		if(!action) action="init";
		
		return $(this).each(function() {
			$this = $(this);
			// build element specific options
			var o = $.metadata ? $.extend({}, opts, $(this).metadata()) : opts;
		
			//$this.data("image-uploader",o); 
			
			switch(action){
				case "init":
					//return $(this).each(function(i,elem){
						//var $itm= $(this);
						//console.dir({'itm':{o:o}});
						var this_itm= items[o.itmid];
						//console.dir({thisitem:this_itm});
						$this.attr("id",'i_'+o.itmid).addClass("item").show();
						if(this_itm.src.length){
							var src= unescape(this_itm.src).replace("/orig","/125x125").replace("/orig_","/125x125_");
							$this.find("img").attr({src:src});
							if(this_itm.tmbw>0) $this.find("img").attr({width:this_itm.tmbw});
							if(this_itm.tmbh>0) $this.find("img").attr({height:this_itm.tmbh});
						} else {
							$this.find("img").attr({src:imgnotfound,width:'125',height:'125'});
						}
						$this.click(function(e){
							//console.dir({clicked:$(this).metadata()});
							if($(this).hasClass("loaded")) return false;
							$itm= $(this);
							itmidx = $itm.parent().children().index($itm[0]);
							itmid= $itm.metadata().itmid;
							itm= items[itmid];
							//itm_api.select(itmidx,'item',false);
							var $img= $itm.find("img");
							//console.dir({itmidx:itmidx,itm_si:itm_api.getSelectedIndex()});
							var $wrap = $("#gallery .xk_itm").fadeTo("medium", 0.5);
							var str='';
							src= unescape(itm.src).replace("/orig","/350x350").replace("/orig_","/350x350_");
							var img = new Image();
							img.onload = function() {
								$wrap.fadeTo("fast", 1);
								$("#bigimg-holder img").attr({src:src,width:itm.lrgw,height:itm.lrgh})
										
							};
							img.src = src;
							
							var lrgImg = new Image();
							lrgImg.src= unescape(itm.src);
							$("#xtrLrg").css({width:itm.ow+16+'px'});
							$("#xtrLrg img").attr({src:unescape(itm.src),width:itm.ow,height:itm.oh});
							$("#xtrLrg h2").text(unescape(itm.name));
							
							var html= _itmHTML(itm);
							$("#bigimg-details").html(html);
							$("#bigimg-details").ecartItems();
							
							$itm.siblings().removeClass("loaded");
							$itm.addClass("loaded");
						});	// end of click()						
				break;
			}			
		 });
	};
	
	function _itmHTML(itm){
		var html="<h2>"+itm.name+"</h2>";
		html+="<p class='medium'>"+itm.medium+"</p>";
		html+="<p class='size'>"+itm.size+"</p>";
		itm.is_forsale= itm.is_forsale;
		itm.is_sold= itm.is_sold;
		var str;
		for(i in itm) str+="\n"+i+":"+typeof (itm[i]);
		
		col= collections[itm.collectionid];
		
		if(itm.cur_price>0) {
			html+="<p class='price'>$"+itm.cur_price;
			if(itm.is_forsale && !itm.is_sold)html+=" <a href='#' class=\"cartItem price\"></a>";
			html+="</p>";
		}
		if(itm.cur_price_framed>0) {
			html+="<p class='price_framed'>$"+itm.cur_price_framed+" with frame";
			if(itm.is_forsale && !itm.is_sold) html+=" <a href='#' class=\"cartItem price_framed\"></a>";
			html+="</p>";
		}
		if(itm.is_forsalegallery) {
			html+="<p class='is_forsalegallery'>Available for purchase on ";
			if(col.url.length) html+=" <a href='"+col.url+"' target=\"_blank\" class=\"is_soldgallery\">";
			html+="Gallery Website";
			if(col.url.length) html+="</a>";
			html+="</p>";
		}
		if(itm.is_sold){
			html+="<p class=\"sold\">SOLD</p>";
		}
		//if(console) console.dir({itm:itm})
		//if(console) console.dir({si:shipinfo})
		var si='';
		if(parseInt(itm.shipinfoid)) si= shipinfo[parseInt(itm.shipinfoid)]['te_info'];
		if(itm.te_shipinfo.length) si= itm.te_shipinfo;
		if(si.length) html+="<p class=\"shipinfo\">"+unescape(si)+"</p>";
		html+="<p class='descr'>"+itm.ta_description+"</p>";
		;
		return html;
	}
	
	function _ecartItems(){
		var count=0,ttl=0,ttl_price=0,i={},framed=false,html='<table class=ecart>',descr='',collectionName='',price=0,shipping=0,wshipping=0,ttl_shipping=0;
		html+="\n<tr><th></th><th>Item#</th><th>Collection</th><th>Item Name</th><th class=price>Price</th><th>&nbsp;</th></tr>";
		//console.dir({'ecart':ecart});
		for(var x=0;x<=ecart.length;x++){
			if(ecart[x]!==undefined){
				i= items[x];
				count++;
				framed= ecart[x];
				shipping=0;
				price= i.cur_price;
				wshipping= i.cur_shipping;

				console.dir({i:i});
				//console.dir({collections:collections});
				collectionName= collections[i.collectionid].collectionName;
				if(framed) {
					price= i.cur_price_framed;
					wshipping= i.cur_shipping_framed;

				}
				tmbsrc= i.src.replace("orig_","125x125_").replace("orig/","125x125/");
				ttl_price+=price;
				descr = i.name+"";
				if(framed) descr+= " FRAMED";
				html+="\n<tr class=ecart_item>";
				html+="<td class=thumbnail><img src='"+tmbsrc+"' width=30 class='{itmid:"+x+",colid:"+i.collectionid+"}'/></td>";
				html+="<td class=itmid>";
				html+='<input type="hidden" name="item_name_'+count+'" value="'+descr+' ('+x+')">';
				html+='<input type="hidden" name="amount_'+count+'" value="'+price+'">';
				html+='<input type="hidden" name="quantity_'+count+'" value="1">';
				if(wshipping>0){
					shipping= wshipping-price;
					ttl_shipping+= wshipping;
					html+='<input type="hidden" name="shipping_'+count+'" value="'+wshipping+'">';
				}
				html+=''+x+'</td>';
				html+='<td class=collectionName>'+collectionName+'</td>';
				html+='<td class=itemName>'+descr+'</td>';
				html+='<td class=price>'+numberFormat(price,"$")+'</td>';
				//html+='<td class=shipping>'+numberFormat(wshipping,"$")+'</td>';
				html+='<td class=remove><a href="#" class="removeItem {itmid:'+x+'}">[Remove]</a></td>';
				html+='</tr>';
				
			}
		}
		ttl= ttl_price+ttl_shipping;
		$("#ecart").data("itemcount",count);
		$("#itemcount").text("("+count+")");
		html+='<tr><td></td><td></td><td></td><td class="total">Totals</td>';
		html+='<td class="price total">'+numberFormat(ttl_price,"$")+'</td>';
		//html+='<td class="price total">'+numberFormat(ttl_shipping,"$")+'</td>';
		html+='<td class="price total"></td></tr>';
		var btn= '<input type="image" src="http://www.paypal.com/en_US/i/btn/x-click-but01.gif" name="submit" alt="Make payments with PayPal">';
		html+='<tr><td></td><td></td><td></td><td></td><td class="price">'+btn+'</td></tr>';
		return html+='</table>';
	}
	
	$.fn.ecart= function(){
		
		return this.each(function(){
				$this=$(this);				  
				$("#ecart_items",$this).html(_ecartItems());
				$("table.ecart td.thumbnail img").click(function(){
						var iid= $(this).metadata().itmid;
						var cid= $(this).metadata().colid;
						$("#toggleEcart").click();
						//console.dir({cid:cid,iid:iid,img:this,col:$(".col_"+cid)});
						$(".col_"+cid).trigger("click.collection");
						$("#i_"+iid).click();
						
						});
				$("a.removeItem",$this).bind("click.ecartItem",function(e){
						var id= $(this).metadata().itmid;
						//console.dir({this:this});
						//console.dir({id:id});
						ecart.splice(id,1);
						$("#bigimg-details").ecartItems();
						//console.dir({ecart_remove:ecart});
						var frm={handler:'ecartRemoveItem',itmid:itmid};
						$("#ecart").ecart();
						$.post("ajax.php", frm,dump,'json');
						return false;
						});
			});
	};
		
	$.fn.ecartItems= function(){
		$this= $(this);
		//$this.data("itm",itm);
		$("a.cartItem",$this).each(function(){
			$a= $(this);
			$a.unbind("click.ecartItem").text("");
			var framed= $a.hasClass("price_framed");
			
			if(ecart[itmid]!==undefined){
				if(framed === ecart[itmid]){
					$a.text("[Remove from Cart]");
					$a.bind("click.ecartItem",function(e){
						ecart.splice(itmid,1);
						$("#bigimg-details").ecartItems();
						//console.dir({ecart_remove:ecart});
						var frm={custom_handler:'ecartRemoveItem',itmid:itmid};
						$("#ecart").ecart();
						$.post("ajax.php", frm,dump);
						return false;
						});
				}
			} else {
				$a.text("[Add to Cart]");
				$a.bind("click.ecartItem",function(e){
					ecart[itmid]=framed;
					$("#bigimg-details").ecartItems();
					//console.dir({ecart_add:ecart});
					var frm={custom_handler:'ecartAddItem',itmid:itmid,framed:framed};
					$("#ecart").ecart();
					$.post("ajax.php", frm,dump);
					return false;
					});
			}
			});
		return $this;
	}
							
	$.fn.collectionItem.defaults= {
		itmid:0
	};
	
	
	$.fn.collectionsScrollable= function(state){
		
		if(state){
			
			$("#backToCollections").removeClass("hidden").show();
			$("#collectionName").removeClass("hidden").show();
			$("#gallery").slideDown();
			$("#collections").slideUp();
			/*
			$("#collections").addClass("scrollable");
			var div= $("#collections");
			$(".browse",div).addClass("browse-scrollable");
			$(".xk_pub",div).each(function(e){ 
					$(this).data('w',$(this).width()).data('h',$(this).height());
					//$('.ui-state-disabled',this).removeClass('ui-state-disabled');
					$(this).stop().animate({
						height: 52,
						width: '20000em'
					  }, 500, 'swing', function() {
						$(this).addClass("xk_pub-scrollable");
					  });
				});
			$(".mx_pub",div).each(function(e){ 
					//console.dir({'h before':$(this).height()});
					
					$(this).data('w',$(this).width()).data('h',$(this).height());
					$(this).css({height:$(this).height()+'px'});
					//console.dir({'h after':$(this).height()});
					$(this).addClass("mx_pub-scrollable");
					$(this).stop().animate({
						width: 720,
						height: 52
					  }, 500, 'swing', function() {
						//var col_api = $("#collections div.mx_pub").data("scrollable");
						//col_api.seekTo(col_api.getSelectedIndex());
					  });
				});
			
			$(".rg_imageid",div).slideUp(0);
			
			$(".rg_ta_description",div).each(function(e){
				$(this).data('w',$(this).width()).data('h',$(this).height());
				//console.dir({'tmbw':$(this).data('tmbw'),'tmbh':$(this).data('tmbh')});
				$(this).stop().animate({
					width: 170
				  }, 0, 'swing', function() {
					// Animation complete.
				  });
			});
			*/

		} else {
			$("#backToCollections").hide();
			$("#collectionName").show();
			$("#gallery").stop().slideUp();
			$("#collections").stop().slideDown();
			/*
			$("#collections").removeClass("scrollable");
			$(".browse",div).removeClass("browse-scrollable");
			$(".xk_pub",div).removeClass("xk_pub-scrollable").each(function(e){ 
					//console.dir({xbkt:{w:$(this).data('w'),h:$(this).data('h')}});
					var w = $(this).data('w');
					var h = $(this).data('h');
					
					//$(this).find(".xblok").each(function(){ init(this); });
					$(this).stop().animate({
						width: w,
						height: h
					  }, 500, 'swing', function() {
						// Animation complete.
						init(this);
					  });
				});
			$(".mx_pub",div).each(function(e){ 
										 
					var w = $(this).data('w');
					var h = $(this).data('h');
					$(this).removeClass("mx_pub-scrollable");
					//console.dir({moxblok:{w:$(this).data('w'),h:$(this).data('h')}});
					$(this).stop().animate({
						width: 831,
						width: h
					  }, 500, 'swing', function() {
						$(this).css({height:'auto'});
						init(this);
					  });
				});
			$(".rg_imageid",div).slideDown(0);
			
			$(".rg_ta_description",div).each(function(e){
				//console.dir({descr:{w:$(this).data('w'),h:$(this).data('h')}});
				var w = $(this).data('w');
				var h = $(this).data('h');
				$(this).stop().animate({
					width: w
				  }, 0, 'swing', function() {
					//$(this).css({height:'auto'});
				  });
			});
			*/
			
		}
	};
	
})(jQuery);



