﻿var Case={
	init:function () {
		$("case-info").addReplacingEvent("click",function (e) { Case.open(); });

		//dbg Case.open();

		$(document.body).addEvent("keydown",function (e) {
			if (Case._isOpened && e.key=="esc") {
				if (Tooltip._isOpened) Tooltip.hide();
				else Case.close();
			}
		});

		if (typeof(Ads)!="undefined") Ads.addEvent("onSearching",function () {
			Case.close();
		});
		if (typeof(FullAd)!="undefined") FullAd.addEvent("onOpening",function () {
			Case.close();
		});
	},

	_listElement:null,
	_initContentsInterface:function () {
		Case._listElement=$("case-contents-list");
		Case._initCloseButton();
		Case._initActions();
		Case._initPaging();
	},

	_initCloseButton:function () {
		var closeButton=$("case-contents").getElement(".close");
		if (closeButton.retrieve("closingEvent")) return;
		closeButton.store("closingEvent",true);
		closeButton.addReplacingEvent("click",function (e) { Case.close(); });
	},

	_initActions:function () {
		var list=$("case-contents-list");
		list.getElements(".delete").addReplacingEvent("click",function (e) {
			var actionElement=this.getParent("li"),
				adId=+actionElement.id.split("-")[1], // a id in format adaction-47
				adElement=list.getElement(".ad-"+adId);

			Case.confirmRemove(adId,this,function () {
				actionElement
					.retrieveOrStore("fx",function () { return this.effects(); })
					.start({height:0,opacity:0}).chain(function () {
						actionElement.retrieve("fx").start({width:0,marginRight:0});
						adElement.setStyle("overflow","hidden").effects().start({width:0,opacity:0,marginRight:0}).chain(function () {
							adElement.dispose();
							actionElement.dispose();
							// move the current one to the previous one
							Case._currentAdIndex=Math.max(0,Case._currentAdIndex-1);
							Case._initPaging();
						});
					});
			});
		});
		
		$("case-contents-list").getElements(".notes").addReplacingEvent("click",function (e) {
			var adId=this.getParent("li").id.split("-")[1]; // a id in format adaction-47
			Case._showNotes(adId,this);
		});
		
		$("case-contents-list").getElements(".ads>li").addReplacingEvent("click",function () {
			var adId=+this.id.split("-")[1]; // id in format ad-44
			FullAd.open(adId);
		});
	},

	/**************************
	*** Paging and elements ***
	**************************/

	PAGE_SIZE:5,
	_currentAdIndex:0,

	// this function draws the page numbers and prepares the functions of paging
	_initPaging:function () {
		var elements=$E("#case-contents-list .ads").getElements("li");

		var pageCount=Math.ceil(elements.length/Case.PAGE_SIZE);

		// page numbers
		var pages=new Elements();
		pageCount.times(function (idx) {
			pages.push(
				new Element("li")
				.adopt(
					new Element("a",{
						href:"#",
						events:{ click:function (e) { e.stop(); Case._currentAdIndex=idx*Case.PAGE_SIZE; Case.goToAd(Case._currentAdIndex); } }
					})
					.set("text",idx+1)
				)
			);
		});
		var currPageIdx=Math.floor(Case._currentAdIndex/Case.PAGE_SIZE);
		if (pages[currPageIdx]) {
			pages[currPageIdx].addClass("current");
			Case._lastPageElement=pages[currPageIdx];
		}

		// first, remove any page elements if exist, without the next/prev
		var currentPageElementsToRemove=$("case-contents-paging").getElements("li");
		currentPageElementsToRemove.shift(); // prev link
		currentPageElementsToRemove.pop(); // next link
		currentPageElementsToRemove.dispose(); // remove all other children

		// inject them before next button
		pages.inject($("case-contents-paging").getElement("li:last-child"),"before");

		// next-back of paging
		if(pageCount > 1){
			$("case-contents-paging").getElement(".prev").addReplacingEvent("click",function (e) {
				Case.stepToAd(-Case.PAGE_SIZE);
			});
			$("case-contents-paging").getElement(".next").addReplacingEvent("click",function (e) {
				Case.stepToAd(Case.PAGE_SIZE);
			});

			// next-back of ads
			$("case-contents-previous").addReplacingEvent("click",function (e) {
				Case.stepToAd(-1);
			});
			$("case-contents-next").addReplacingEvent("click",function (e) {
				Case.stepToAd(1);
			});
		}
		else{
			$("case-contents-paging").style.display = "none";
			$("case-contents-previous").style.display = "none";
			$("case-contents-next").style.display = "none";
			
		}
	},
	_setNextPrevState:function () {
		
	},
	stepToAd:function (step) {
		Case._currentAdIndex+=step;
		Case._currentAdIndex=Case.goToAd(Case._currentAdIndex);
	},
	goToAd:function (index) {
		Tooltip.hide();

		var elements=$E("#case-contents-list .ads").getElements("li");
		
		index=index.limit(0,elements.length-1);

		var pages=$("case-contents-paging").getElements("li");
		pages.pop(); pages.shift();

		//if ((index%Case.PAGE_SIZE)>0) alert('x');

		if (!elements[index]) return;

		Case._listElement.retrieveOrStore("fxScroll",function () {
			return new Fx.Scroll(this,{wheelStops:false,transition:Fx.Transitions.Expo.easeOut});
		}).toElement(elements[index]);
		if (Case._lastPageElement) Case._lastPageElement.removeClass("current");
		// the new page calculated by the current ad index
		var currPage=pages[Math.floor(index/Case.PAGE_SIZE)];
		currPage.addClass("current");
		Case._lastPageElement=currPage;
		
		return index;
	},

	/**************************
	*** Opening and closing ***
	**************************/

	_isOpened:false,
	open:function () {
		//new Fx.Slide($("case-contents")).show();
		if (Case._isOpened) return; Case._isOpened=true;

		//if (Case._contentsSourceArrived) { Case._slideInCase(); return; }

		Case.fireEvent("onOpening");

		Mantis.EyeBlaster.Services.CaseService.GetCaseContentsSource(function (source) {
			Case._contentsSourceArrived=true;
			$("case-wrap").addClass("caseOpened");
			$("case-contents-placeholder").setHTML(source);
			Case._initContentsInterface();
			Case._slideInCase();

			Case.fireEvent("onOpened");
		});
	},
	// lightbox-like overlay
	_overlay:null,
	_showOverlay:function () {
		if (!Case._overlay) Case._overlay=new Element("div",{
			styles:{
				position:"absolute",
				left:0,
				backgroundColor:Lightbox.prototype.options.backgroundColor,
				opacity:Lightbox.prototype.options.opacity,
				width:"100%"
			}
		}).injectBefore($("case"));
		Case._overlay.show().setStyles({height:document.getScrollSize().y-$("case").getPosition().y});
	},
	_hideOverlay:function () {
		Case._overlay.hide();
	},
	_slideInCase:function () {
		Case._showOverlay();

		var firstTime=false;
		var wrapper=$("case-contents").retrieveOrStore("wrapper",function () {
			firstTime=true;
			return new Element("div",{
				styles:{
					position:"absolute",
					overflow:"hidden"
				}
			})
			.wraps(this);
		}).show();
		$("case-contents").setVisibility(false).show().setStyles({top:-$("case-contents").scrollHeight-50});
		if (firstTime) wrapper.setStyles({
			height:$("case-contents").scrollHeight,
			width:$("case-contents").offsetWidth
		});
		$("case-contents").setVisibility(true).retrieveOrStore("fx",function () {
			return this.effect("top",{transition:Fx.Transitions.Quint.easeInOut,duration:1000});
		}).start(0);
	},

	close:function () {
		if (!Case._isOpened) return;
		$("case-contents").retrieve("fx").start(-$("case-contents").scrollHeight-50).chain(function () {
			$("case-contents").hide();
			$("case-contents").retrieve("wrapper").hide();
			$("case-wrap").removeClass("caseOpened");
			Case._isOpened=false;
		});
		Case._hideOverlay.delay(500);
	},

	/**************************
	*** Adding and removing ***
	**************************/

	add:function (adId,relative,callback) {
		if (!UserManager.logged) {
			UserManager.login({invalidAction:true});
			return;
		}

		userAdFolder="all";

		var clone=new Element("div")
			.addClass("caseAddClone")
			.inject(document.body)
			.setStyles({opacity:.7})
			.position(relative.getPosition());
		var casePosition=$("case-number").getPosition();
		// move clone to half of the number element
		casePosition.y-=$("case-number").offsetHeight/2;
		clone
			.effects({transition:Fx.Transitions.Expo.easeInOut})
			// move clone
			.start({left:casePosition.x,top:casePosition.y}).chain(function () {
				// then fade it
				this.start({opacity:0}).chain(function () {
					// the delete it
					clone.dispose();
				});

				// then make the number with 'updating case' status
				$("case-number").addClass("updating");

				// add by ajax
				Mantis.EyeBlaster.Services.CaseService.CaseAdd(adId,userAdFolder,function (newAmount) {
					Case._setAmount(newAmount);
					$("case-number").removeClass("updating");

					Case._pulsateCaseNumber();
					
					if (callback) callback();
				});
			});
	},
	_setAmount:function (amount) {
		$$("#case-number-amount,#case-contents-number-amount").set("text",amount);
	},
	_pulsateCaseNumber:function () {
			// then pulsate the number
			var fx=$("case-info").retrieveOrStore("fxPulse",function () { return this.effect("opacity",{duration:150}) });
			function fadeIn() { return fx.start(1); }
			function fadeOut() { return fx.start(0); }

			return fadeOut()
				.chain(fadeIn).chain(fadeOut)
				.chain(fadeIn).chain(fadeOut)
				.chain(fadeIn);
	},
	move:function (adId,userAdFolder,btn) {
		Mantis.EyeBlaster.Services.CaseService.CaseAdd(adId,userAdFolder,function (affected) {
			alert(affected);
		});
	},
	_initConfirmRemoveElement:function (onRemove,onCancel) {
		var yes=$("delete-tooltip-content").getElement(".yes"),
			no=$("delete-tooltip-content").getElement(".no");
		yes.addReplacingEvent("click",function (e) {
			Case.remove(Case._currentAdSelectedForDelete,onRemove);
		});
		no.addReplacingEvent("click",function (e) {
			onCancel();
		});
	},
	confirmRemove:function (adId,relative,onRemove) {
		Case._currentAdSelectedForDelete=adId;
		Case._currentOnRemoveAd=onRemove;
		if (!Case._initConfirmRemoveElementFired) {
			Case._initConfirmRemoveElement(
				function () {
					Case._currentOnRemoveAd();
					Case._currentOnRemoveAd=null;
					Case._currentAdSelectedForDelete=null;
					Tooltip.hide();
				},function () {
					Case._currentOnRemoveAd=null;
					Case._currentAdSelectedForDelete=null;
					Tooltip.hide();
				});
			Case._initConfirmRemoveElementFired=true;
		}
		Tooltip.show("delete",relative);
	},
	remove:function (adId,callback) {
		Mantis.EyeBlaster.Services.CaseService.CaseRemove(adId,function (newAmount) {
			Case._setAmount(newAmount);
			Case._pulsateCaseNumber();
			if (callback) callback();
		});
	},

	/************
	*** Notes ***
	*************/

	_currentNotesAdId:null,
	_initNotesForm:function () {
		$("notes-form").addReplacingEvent("submit",function (e) {
			Case.saveNotes(Case._currentNotesAdId,this["notes"].value);
		});
	},
	_showNotes:function (adId,relative) {
		Case._initNotesForm.callOnce();
		Case._currentNotesAdId=adId;
		Case.getNotes(adId,function () {
			Tooltip.show("notes",relative);
		});
	},
	getNotes:function (adId,callback) {
		Mantis.EyeBlaster.Services.CaseService.GetAdNotes(adId,function (notes) {
			$("notes-form")["notes"].value=notes || "";
			callback();
		});
	},
	saveNotes:function (adId,notes) {
		var time=$time();
		$("notes-form")["notes"].disabled=true;
		Mantis.EyeBlaster.Services.CaseService.SetAdNotes(adId,notes,function () {
			var timeDiff=$time()-time;
			if (timeDiff<500) timeDiff=500;
			(function () {
				$("notes-form")["notes"].disabled=false;
			}).delay(timeDiff);
		});
	}
};

Events.makeObjectEventable(Case);
$DL(Case.init);

var Tooltip={
	_isOpened:false,
	_initialized:false,
	_init:function () {
		$("case-tooltip").getElement(".tooltip-close").addReplacingEvent("click",function (e) {
			Tooltip.hide();
		});
	},
	show:function (name,relative) {
		Tooltip._isOpened=true;
		Tooltip._init.callOnce();
		var pos=relative.getRelativePosition($("case-contents"));
		pos.y-=33;
		pos.x+=90-Case._listElement.getScroll().x;
		$("case-tooltip").show().position(pos);
		$("case-tooltip").getElement(".tooltip-content").getChildren().hide();
		$("case-tooltip").getElement("."+name).show();
	},
	hide:function () {
		if (Tooltip._isOpened) {
			$("case-tooltip").hide();
			Tooltip._isOpened=false;
		}
	}
};
