AUI().add('ltt-history-panel', function(A){	
	var WISHLIST_SLCTR,
		VIEWLIST_SLCTR,
		SHOPPINGCART_SLCTR,
		HIDER_SLCTR = "#_bp_WAR_lttportlet_tf_hp_body_hider",
		GETTER_STATE_FROM_HIDER_SLCTR = "#_bp_WAR_lttportlet_tf_hp_iwrapper",
		OPENED_STATE_CLASSNAME = "tf-hp-opened",
		TAB_CNTRLS_HLDR_SLCTR = "#_bp_WAR_lttportlet_tf_hp_tabs_controls",
		TAB_CNTRL_SLCTR = ".tf-hp-tab-control",
		TAB_INACTIVE = "tf-hp-tab-control-inactive",
		TAB_CNTRL_SWTCHR_SLCTR = ".tf-hp-tc-lnk",
		TAB_SLCTR = ".tf-hp-tab",
		SELECTED_CLASSNAME = "selected",
		TAB_WISHLIST_SLCTR = "#_bp_WAR_lttportlet_tf_hp_wishlist_tab",
		TAB_VIEWLIST_SLCTR = "#_bp_WAR_lttportlet_tf_hp_viewlist_tab",
		TAB_SHOPPINGCART_SLCTR = "#_bp_WAR_lttportlet_tf_hp_shoppingcart_tab",
		WISHLIST_COUNT_HLDR_SLCTR = "#_bp_WAR_lttportlet_tf_hp_wishlist_count",
		VIEWLIST_COUNT_HLDR_SLCTR = "#_bp_WAR_lttportlet_tf_hp_viewlist_count",
		SHOPPINGCART_COUNT_HLDR_SLCTR ="#_bp_WAR_lttportlet_tf_hp_shoppingcart_count",
		SLIDER_SLCTR = ".tf-hp-slider",
		
		ADoc = A.one("document");
	
	
	A.LttHistoryPanel = new A.Component.create({
		NAME: "LttHistoryPanel",
		EXTENDS: A.Component,
		HTML_PARSER: {
			hiderNode: function(srcNode){
				return srcNode.one(HIDER_SLCTR);
			},
			tabCtrlsHldrNode: function(srcNode){
				return srcNode.one(TAB_CNTRLS_HLDR_SLCTR);
			}, 
			selectedTabCtrlNode: function(srcNode){
				return srcNode.one(TAB_CNTRL_SLCTR+"." + SELECTED_CLASSNAME);
			},
			selectedTabNode: function(srcNode){
				return srcNode.one(TAB_SLCTR+"." + SELECTED_CLASSNAME);
			}				
		},
		ATTRS: {
			hiderNode: {},
			minimized: {value: true},
			minimizedHeight: {value: 42},
			maximizedHeight: {value: 132},
			anim: {},
			anim2: {},
			expandingTime: {
				value: 0.5
			},
			initFooterPadding: {},
			expFooterPadding: {},
			copyrightHeight: {},
			floatingNode: {},
			tabCtrlsHldrNode: {},
			selectedTabCtrlNode: {},
			selectedTabNode: {},
			wishListSlider: {},
			viewListSlider: {},
			shoppingcartSlider: {},
			resourcesURL:{},
			itemTmpltHldrSlctr: {
				value: "#tf_hp_item_template"
			},
			itemShdlTmpltHldrSlctr: {
				value: "#tf_hp_item_shdl_template"
			},
			itemShdlItemTmpltHldrSlctr: {
				value: "#tf_hp_i_shdl_i_template"
			},
			itemTmplt: {},
			itemShdlTmplt: {},
			itemShdlItemTmplt: {}
		},
		prototype: {
			initializer: function(){
				var itemTmpltHldr = A.one(this.get('itemTmpltHldrSlctr')),
					itemShdlTmpltHldr = A.one(this.get('itemShdlTmpltHldrSlctr')),
					itemShdlItemTmpltHldr = A.one(this.get('itemShdlItemTmpltHldrSlctr')),
					itemTmplt = itemTmpltHldr.html(),
					itemShdlTmplt = itemShdlTmpltHldr.html(),
					itemShdlItemTmplt = itemShdlItemTmpltHldr.html();
				this.set("itemTmplt", itemTmplt);
				this.set("itemShdlTmplt", itemShdlTmplt);
				this.set("itemShdlItemTmplt", itemShdlItemTmplt);

				this.set('floatingNode', A.one(GETTER_STATE_FROM_HIDER_SLCTR));
				this._initExpdingAnim();				
			},
			_initExpdingAnim: function(){
				var instance = this,
					anim = new A.Anim({
						node: instance.get('floatingNode'),
						duration: instance.get('expandingTime')
					}),
					footer = A.one("#footer .footer");
				var	anim2 = new A.Anim({
						node: footer,
						duration: instance.get('expandingTime')
					}),
					initPadding = parseInt(footer.getStyle('paddingBottom'));
				instance.set('initFooterPadding', initPadding);
				instance.set('expFooterPadding', initPadding + instance.get('maximizedHeight')-instance.get('minimizedHeight'));
				instance.set('copyrightHeight', parseInt(footer.getStyle('paddingTop')) + parseInt(footer.getStyle('height')));
				
				instance.set('anim', anim);
				instance.set('anim2', anim2);
			},
			_initSliders: function(){
				var instance = this;
					resourcesURL = instance.get('resourcesURL').replace('TIMESTAMP_PLACEHOLDER', new Date().getTime());
				
				A.io(resourcesURL, {
					method: 'GET',			   
					on: {
						complete: function(id, o, args){
							try{
	                            var callback = A.JSON.parse(o.responseText);
	                            if(callback.wishList && callback.viewList){
									var contentBox = instance.get('contentBox'),
										itemTmpltHldrSlctr = instance.get('itemTmpltHldrSlctr'),
										itemTmpltHldr = A.one(itemTmpltHldrSlctr);
	                            	
									
									
								   	var wishListSlider = new A.LttHPSlider({
	            						srcNode: contentBox.one(TAB_WISHLIST_SLCTR + " "+SLIDER_SLCTR),
	            						slidesObjs: (callback.wishList && A.Lang.isArray(callback.wishList))?callback.wishList:[],
	            						itemTmplt: instance.get("itemTmplt"),
										itemShdlTmplt: instance.get("itemShdlTmplt"),
										itemShdlItemTmplt: instance.get("itemShdlItemTmplt"),
										countIndctrNode: WISHLIST_COUNT_HLDR_SLCTR
	                            	});
	                            	var viewListSlider = new A.LttHPSlider({
	            						srcNode: contentBox.one(TAB_VIEWLIST_SLCTR + " "+SLIDER_SLCTR),
	            						slidesObjs: (callback.viewList && A.Lang.isArray(callback.viewList))?callback.viewList:[],
	            						itemTmplt: instance.get("itemTmplt"),
										itemShdlTmplt: instance.get("itemShdlTmplt"),
										itemShdlItemTmplt: instance.get("itemShdlItemTmplt"),
										countIndctrNode: VIEWLIST_COUNT_HLDR_SLCTR
	            					});
	                            	var shoppingcartSlider = new A.LttHPSlider({
	            						srcNode: contentBox.one(TAB_SHOPPINGCART_SLCTR + " "+SLIDER_SLCTR),
	            						slidesObjs: (callback.scart && A.Lang.isArray(callback.scart))?callback.scart:[],
	            						itemTmplt: instance.get("itemTmplt"),
										itemShdlTmplt: instance.get("itemShdlTmplt"),
										itemShdlItemTmplt: instance.get("itemShdlItemTmplt"),
										countIndctrNode: SHOPPINGCART_COUNT_HLDR_SLCTR
	            					});
									instance.set('wishListSlider', wishListSlider);
	                            	instance.set('viewListSlider', viewListSlider);
	                            	instance.set('shoppingcartSlider', shoppingcartSlider);
	                            	
									var floatingNode = instance.get("floatingNode");
									floatingNode.setStyle("height", "0");
									floatingNode.show();
									
	                            	
									wishListSlider.render();
	                				viewListSlider.render();
	                				shoppingcartSlider.render();									
									
									var anim = instance.get('anim'),
										anim2 = instance.get('anim2');
	                				anim.set('to', { height: instance.get('minimizedHeight') + "px" });					
									anim.on('end', function() {
										instance.set('minimized', true);										
									});
									anim2.set('to', { paddingBottom: instance.get('initFooterPadding') + "px" });					
									
									anim.run();
									anim2.run();
	                            }else{
	                                A.fire('io:failure',{id:id, response: callback});                                                                                
	                            }
							}catch (e) {
                        		A.fire('io:failure',{id:id, response: A.dump(e)});
							}                        
						} 
					}
				});
				
								 
				
			},
			renderUI: function(){
				var instance = this;
								
			},
			bindUI: function(){	
				this._bindHiding();
				this._bindTabbing();
				this._bindItemsRegenarationOnOutworldChange();
			},
			_bindHiding: function(){
				var instance = this,
					anim= instance.get('anim'),
					anim2= instance.get('anim2');
				instance.on("minimizedChange", function(e){
					if(e.newVal){
						instance.get('floatingNode').removeClass(OPENED_STATE_CLASSNAME);
					}else
						instance.get('floatingNode').addClass(OPENED_STATE_CLASSNAME);
				});
				var cpHeight = instance.get('copyrightHeight');
				
				instance.get('hiderNode').on("click", function(e){
					if(instance.get('floatingNode').hasClass(OPENED_STATE_CLASSNAME)){
						anim.set('to', { height: instance.get('minimizedHeight') + "px" });					
						anim.on('end', function() {
		                	instance.set('minimized', true);
						});
						anim2.set('to', { paddingBottom: instance.get('initFooterPadding') + "px" });						
						anim.run();	
						anim2.run();
					}else{
						anim.set('to', { height: instance.get('maximizedHeight') + "px" });					
						anim.on('end', function() {
		                	instance.set('minimized', false);
						});
						anim2.set('to', { paddingBottom: instance.get('expFooterPadding') + "px" });
						var docHeight = ADoc.get('docHeight');
						if((docHeight-ADoc.get('docScrollY'))< (ADoc.get('winHeight')+cpHeight)){
							anim2.after('tween', function(){														 
								window.scroll(0, docHeight);
							});
						}else{
							anim2.detach('tween');
						}
						anim2.run();
						anim.run();
					}					
					instance.set('minimized', instance.get('floatingNode').hasClass(OPENED_STATE_CLASSNAME));
				});
			},
			_bindTabbing: function(){
				var instance = this;
				instance.get('tabCtrlsHldrNode').delegate('click', function(e){
					e.preventDefault();
					var ctrl = e.target.ancestor(TAB_CNTRL_SLCTR);
						curSlctdCtrl = instance.get('selectedTabCtrlNode');
					if(!ctrl.hasClass(TAB_INACTIVE)){	
						if(instance.get('minimized')){
							instance.get('hiderNode').simulate('click');
						}
	
						if( ctrl != curSlctdCtrl ){
							curSlctdCtrl.removeClass(SELECTED_CLASSNAME);
							instance.get('selectedTabNode').removeClass(SELECTED_CLASSNAME);
							
							var tabId = (e.target.test('a'))?e.target.getAttribute('rel'):e.target.ancestor('a').getAttribute('rel');
							
							var newSel = A.one("#"+tabId);
							ctrl.addClass(SELECTED_CLASSNAME);
							newSel.addClass(SELECTED_CLASSNAME);
							
							instance.set('selectedTabCtrlNode', ctrl);
							instance.set('selectedTabNode', newSel);
						}
					}
				}, TAB_CNTRL_SWTCHR_SLCTR);
			},
			_bindItemsRegenarationOnOutworldChange: function(){
				var instance = this,
					handler = function(e){
						var resourcesURL = instance.get('resourcesURL').replace('TIMESTAMP_PLACEHOLDER', new Date().getTime()),
							resources =  A.JSON.parse(A.io(resourcesURL, {
								method: 'GET',			   
								sync: true 
							}).responseText);
						instance.get('wishListSlider').changeSlides((resources.wishList && A.Lang.isArray(resources.wishList))?resources.wishList:[]);
						instance.get('viewListSlider').changeSlides((resources.viewList && A.Lang.isArray(resources.viewList))?resources.viewList:[]);
						instance.get('shoppingcartSlider').changeSlides((resources.scart && A.Lang.isArray(resources.scart))?resources.scart:[]);
					};
				
				//A.on("history:change", handler);				
				A.on(Liferay.Ltt.eventNames.WISHLIST_CHANGE, handler);
				A.on(Liferay.Ltt.eventNames.VIEWLIST_CHANGE, handler);
			},			
			syncUI: function(){				
				this._initSliders();				
			}
		}
	});
}, '0.5', {
	requires : ['aui-component', 'anim', 'ltt-history-panel-slider']
});

AUI().add('ltt-history-panel-slider', function(A){	
	var ITEMS_HLDR_SLCTR = ".tf-hp-slides",
		ITEM_SLCTR = ".tf-hp-sld-item",
		ITEM_HOVERED_CLSSNM = "tf-hp-sld-item-hovered",
		ITEM_LNK_SLCTR = ".tf-hp-sld-i-lnk",
		ITEM_REMOVER_SLCTR = ".tf-hp-remv-sld-i-lnk",
		ITEM_UNDER_SUN_INDCTR_CLSSNM = "tf-hp-sld-i-undersun",
		SHIFT_SLIDE_PREV_SLCTR = ".tf-hp-sldr-prevCntrl",
		SHIFT_SLIDE_NEXT_SLCTR = ".tf-hp-sldr-nextCntrl",
		INACTIVE_CLSSNM = "inactive",
		ITEM_HVRD_POPUP_HAS_SCHDL_CLSSNM = 'pf-i-has-schedule',
		ITEM_STATUS_1_PRSNT_CLASSNAME = 'pf-itm-stts-indctr-1-set',
		ITEM_STATUS_2_PRSNT_CLASSNAME = 'pf-itm-stts-indctr-2-set',
		ITEM_STATUS_3_PRSNT_CLASSNAME = 'pf-itm-stts-indctr-3-set';
	
	A.LttHPSlider = new A.Component.create({
		NAME: "LttHPSlider",
		EXTENDS: A.Component,
		HTML_PARSER: {
			slidesHolder: function(srcNode){
				return srcNode.one(ITEMS_HLDR_SLCTR);
			},
			/*sliderItemNodes: function(srcNode){
				return srcNode.all(ITEM_SLCTR);
			},*/
			prevSlideCntrlNode: function(srcNode){
				return srcNode.one(SHIFT_SLIDE_PREV_SLCTR);
			},
			nextSlideCntrlNode: function(srcNode){
				return srcNode.one(SHIFT_SLIDE_NEXT_SLCTR);
			}
		},
		ATTRS: {
			itemsPerSlide: {
				value: 4
			},
			slidesQ: {},
			itemsQ: {},
			curSlideNum: {
				value: 1
			},
			itemWidth: {
				value: 191
			},
			slidesHolder: {},
			sliderItemNodes: {},
			prevSlideCntrlNode: {},
			nextSlideCntrlNode: {},
			shiftAnim: {},
			shiftingTime: {
				value: 0.5
			},
			frozen: {
				value: false
			},
			slidesObjs: {},
			itemTmpltHldr: {
				value: "#tf_hp_item_template"
			},
			itemTmplt: {},
			itemShdlTmplt: {},
			itemShdlItemTmplt: {},			
			countIndctrNode: {
				setter: function(val){
					if(!(val instanceof A.Node)){
						if(A.Lang.isString(val)){
							var node = A.one(val);
							if(node){
								return node;
							}else{
								return A.Attribute.INVALID_VALUE;
							}
						}else{
							return A.Attribute.INVALID_VALUE;
						}
					}
					return val;
				}
			}
		},
		prototype: {
			initializer: function(){
				var instance = this;
				
				instance.on("itemsQChange", function(e){
					instance.get('countIndctrNode').set('text', e.newVal);
				});
				
				var shiftAnim = new A.Anim({
					node: instance.get('slidesHolder'),
					duration: instance.get('shiftingTime')						
				});
				shiftAnim.on('start', function(){
					instance.set('frozen', true);
				});
				shiftAnim.on('end', function(){
					instance.set('frozen', false);
				});
				instance.set('shiftAnim', shiftAnim);
				instance.on('frozenChange', function(e){
					
				});				
			},
			renderUI: function(){
				this.changeSlides(this.get('slidesObjs'));								
			},
			changeSlides: function(items){
				var instance = this;
				instance.set('itemsQ', items.length)
				instance.get('slidesHolder').setStyle("width", instance.get('itemWidth')*items.length);
				instance._generateItems(items);
				instance._renderVisibleSlide();
				var curSlideNum = 1;
				instance.set('curSlideNum', curSlideNum);
				instance._updateMoversState(curSlideNum);
			},
			_generateItems: function(items){
				var instance = this,
					itemTmplt = instance.get('itemTmplt'),
					itemShdlTmplt = instance.get('itemShdlTmplt'),
					itemShdlItemTmplt = instance.get('itemShdlItemTmplt'),					
					slidesHolder = instance.get('slidesHolder'),
					itemsQ = items.length;
				instance.set('itemsQ', itemsQ);
				instance.set('slidesQ', Math.ceil(itemsQ/instance.get('itemsPerSlide')));
				
				slidesHolder.empty();
				
				for(var i=0; i<items.length; i++){
					var schedule = "",
						hasSchedule = "",
						indicators = "",
		                rawDates = A.JSON.parse(items[i].dates),
						rdLength = rawDates.length;
					if(rdLength>0){
						var dates = "";
						for(var j=0;j<rdLength;j++){
							var date = new Date(rawDates[j].time),
								day = date.getDate();
							day = (day<10)?"0"+day:day;
							var month = date.getMonth()+1;
							month = (month<10)?"0"+month:month;
							dates += A.Lang.sub(itemShdlItemTmplt,{timeTableItm: day +"." + month + "." + date.getFullYear()});
						}
						schedule = A.Lang.sub(itemShdlTmplt, {timeTable: dates});
						hasSchedule = ITEM_HVRD_POPUP_HAS_SCHDL_CLSSNM;						
					}
					if(items[i].earlyBird)
						indicators+=" "+ITEM_STATUS_1_PRSNT_CLASSNAME;
					if(items[i].lastMinute)
						indicators+=" "+ITEM_STATUS_2_PRSNT_CLASSNAME;
					if(items[i].executionGuaranty)
						indicators+=" "+ITEM_STATUS_3_PRSNT_CLASSNAME;
						
					items[i].hasSchdlClss = hasSchedule;
					items[i].timeTablePart = schedule;
					items[i].insctrs = indicators;
					slidesHolder.append(new A.Node.create(A.Lang.sub(itemTmplt,items[i])));
				}
				instance.set('sliderItemNodes', slidesHolder.get('children'));				
			},
			_renderVisibleSlide: function(slideNum){
				var instance = this,
					curSlideNum = A.Lang.isUndefined(slideNum)?instance.get('curSlideNum'):slideNum,
					itemsPerSlide = instance.get('itemsPerSlide'),
					shift = instance.get('itemWidth')*itemsPerSlide*(curSlideNum-1),
					slidesHolder = instance.get('slidesHolder'),
					sliderItemNodes = instance.get('sliderItemNodes'),
					shiftAnim = instance.get('shiftAnim');
				shift = shift*-1 + "px";
				if(slidesHolder.getStyle('left')!=shift){
					shiftAnim.set("to", {left: shift});
					shiftAnim.run();				
				}
				
				slidesHolder.all("." + ITEM_UNDER_SUN_INDCTR_CLSSNM).each(function(item){
					item.removeClass(ITEM_UNDER_SUN_INDCTR_CLSSNM);
				});
				
				var len = curSlideNum*itemsPerSlide,
					total = instance.get('itemsQ');
				len>total?len=total:"";
				for(var i = (curSlideNum-1)*itemsPerSlide ; i < len; i++){
					sliderItemNodes.item(i).addClass(ITEM_UNDER_SUN_INDCTR_CLSSNM);
				}				
			},			
			bindUI: function(){
				this._bindShifting();
				this._bindItemsHovering();
			},	
			_bindShifting: function(){
				var instance = this;
				instance.on("curSlideNumChange",function(e){
					instance._renderVisibleSlide(e.newVal);
					instance._updateMoversState(e.newVal);
				});
				instance.get('prevSlideCntrlNode').on('click', function(e){
					e.preventDefault();
					if(!instance.get('frozen') && !e.target.hasClass(INACTIVE_CLSSNM)){
						var curSlideNum = instance.get('curSlideNum') - 1;
						instance.set('curSlideNum', curSlideNum);						
					}
				});
				instance.get('nextSlideCntrlNode').on('click', function(e){
					e.preventDefault();
					if(!instance.get('frozen') && !e.target.hasClass(INACTIVE_CLSSNM)){
						var curSlideNum = instance.get('curSlideNum') + 1;
						instance.set('curSlideNum', curSlideNum);						
					}
				});
			},
			_bindItemsHovering: function(){
				var instance = this,
					slidesHolder = instance.get('slidesHolder');
				slidesHolder.delegate("mouseenter", function(e){
					var hovered = e.target;
					if(!hovered.hasClass(ITEM_SLCTR.substr(1)))
						hovered = hovered.ancestor(ITEM_SLCTR);
					hovered.addClass(ITEM_HOVERED_CLSSNM);
				}, ITEM_SLCTR);
				slidesHolder.delegate("mouseleave", function(e){
					var hovered = e.target;
					if(!hovered.hasClass(ITEM_SLCTR.substr(1)))
						hovered = hovered.ancestor(ITEM_SLCTR);
					hovered.removeClass(ITEM_HOVERED_CLSSNM);
				}, ITEM_SLCTR);
			},			
			_updateMoversState: function(curSlideNum){
				var instance = this;
				if(curSlideNum==1){
					instance.get('prevSlideCntrlNode').addClass(INACTIVE_CLSSNM);
				}else{
					instance.get('prevSlideCntrlNode').removeClass(INACTIVE_CLSSNM);
				}				
				var slidesQ = instance.get('slidesQ');
				if(slidesQ==0 || curSlideNum == slidesQ){
					instance.get('nextSlideCntrlNode').addClass(INACTIVE_CLSSNM);
				}else{
					instance.get('nextSlideCntrlNode').removeClass(INACTIVE_CLSSNM);
				}
			},		
			syncUI: function(){
				this._updateMoversState(this.get('curSlideNum'));
			}
		}
	});
}, '0.5', {
	requires : ['aui-component', 'anim']
});
