﻿var FullAd = {
    init: function() {
        FullAd.element = $("fullad");
       
        var currentAdId = QS.get("ItemId");
        if (currentAdId) FullAd.openImmediate(currentAdId);

        var currentAdName = QS.get("ItemName");
        if (currentAdName) {
            Mantis.EyeBlaster.Services.AdService.GetFullAdId(currentAdName, function(result) {
                FullAd._currentAdId = result;
                FullAd.openImmediate(currentAdName);
            });
        }
    },
    initFullOpen: function() {
        Ad.element.getElements(".openFull").addReplacingEvent("click", function(e) {
            FullAd.open(Ads._currentOpenedAdId);
        });
         Ad.element.getElements(".openLiveExample").addReplacingEvent("click", function(e) {
            FullAd.openLiveExampleById(Ads._currentOpenedAdId);
        });

    },
    _isOpened: false,
    open: function(adId) {
        Mantis.EyeBlaster.Services.AdService.GetFullAdHeader(adId, function(adHeader) {
            FullAd.openByName(adHeader);
        });
        /*FullAd._internalOpen(adId);
        Mantis.EyeBlaster.Services.AdService.GetFullAdSource(adId,function (source) {
        Ad.close();
        Ads.hideList();
        new Fx.Scroll(document.documentElement,{wheelStops:false,transition:Fx.Transitions.Expo.easeOut}).toTop().chain(function () {
        FullAd._minimizeHeader();
        FullAd._setElementSource(source);
        });
        });*/
    },
    openLiveExampleById: function(adId){
          Mantis.EyeBlaster.Services.AdService.GetFullAdHeader(adId, function(adHeader) {
            FullAd.openLiveExampleByName(adHeader);
        });
    },
    openByName: function(adName) {
        /*
        Mantis.EyeBlaster.Services.AdService.GetFullAdId(adName, function (adId) {
        if(!isNaN(adId))
        FullAd.open(adId);
        });
        */
        Mantis.EyeBlaster.Services.AdService.GetFullAdId(adName, function(result) {
            FullAd._internalOpen(adName, result);
            Mantis.EyeBlaster.Services.AdService.GetFullAdSource(result, function(source) {         
                Ad.close();
                Ads.hideList();
                FullAd._minimizeHeader();
                new Fx.Scroll(document.documentElement, { wheelStops: false, transition: Fx.Transitions.Expo.easeOut }).toTop().chain(function() {
                    FullAd._setElementSource(source);
                });
            });
        });
    },
    openLiveExampleByName: function(adName){
        Mantis.EyeBlaster.Services.AdService.GetFullAdId(adName, function(result) {
            FullAd._internalOpen(adName, result);
            Mantis.EyeBlaster.Services.AdService.GetFullLiveExampleSource(result, function(source) {
                Ad.close();
                Ads.hideList();
                FullAd._minimizeHeader();
                new Fx.Scroll(document.documentElement, { wheelStops: false, transition: Fx.Transitions.Expo.easeOut }).toTop().chain(function() {
                    FullAd._setElementSource(source);
            });
         });
     });
    },
    openImmediate: function(adId) {
        FullAd._internalOpen(adId);
        FullAd.element.show();
        FullAd._minimizeHeader();
        FullAd._initInterface();
    },
    _internalOpen: function(adName, adId) {

        Ads._currentOpenedAdId = adName;
        FullAd._currentOpenedAdId = adName;
        FullAd._currentAdId = adId;
        FullAd._isOpened = true;
        FullAd.element.store("fxOpen", FullAd.element.effects({ wait: false }));
        FullAd.fireEvent("onOpening", [adName]);
        FullAdChicklets.init();
    },
    _setElementSource: function(source) {
        FullAd.element
			.show()
			.empty()
			.setStyles({ height: 0, opacity: 0, overflow: "hidden" });

        (function() {
            FullAd.element.setHTML(source);

            // wait until html renderes
            var checkRender = (function() {
                if (FullAd.element.scrollHeight == 0) return;
                // when scrollHeight is finally not zero, clear interval
                checkRender = $clear(checkRender);
                var finalHeight = FullAd.element.scrollHeight;

                if (!Browser.Engine.trident4) {
                    FullAd.element.retrieve("fxOpen").start({ opacity: 1, height: finalHeight }).chain(function() {
                        FullAd.element.setStyles({ height: "auto", overflow: "visible" });
                    });
                } else {
                    FullAd.element.setStyles({ height: "auto", overflow: "visible", opacity: 1 });
                }

                FullAd._initInterface();

                FullAd.fireEvent("onOpened");
            }).periodical(50);
        }).delay(10);
    },

    // happens after source arrived
    _initInterface: function() {
        // no use of SmoothScroll since it rewrites the location.href and it breaks the history
        //new SmoothScroll({links:'.anchor',wheelStops:false,transition:Fx.Transitions.Expo.easeOut},FullAd.element);

        FullAd.element.getElements(".anchor").addReplacingEvent("click", function() {
            new Fx.Scroll(document.body, { wheelStops: false, transition: Fx.Transitions.Expo.easeOut }).toElement(this.hash.substr(1));
        });

        $("fullad-add-comment").addReplacingEvent("click", function(e) {
            FullAdComments.toggle();
        });
        $("fullad-button-replay").addReplacingEvent("click", function() {
            $("fullad-template").src = $("fullad-template").src;
        });

        if ($("fullad-button-launch")) {
            $("fullad-button-launch").addReplacingEvent("click", function(e) {
                window.open($("fullad-button-launch").get("href"));
            });
        }
        if ($("fullad-img-launch")) {
            $("fullad-img-launch").addReplacingEvent("click", function(e) {
                window.open($("fullad-img-launch").get("href"));
            });
        }

        AbstractAd.initRater(FullAd.element, FullAd._currentOpenedAdId);
        AbstractAd.initActions(FullAd.element, FullAd._currentAdId);
        AbstractAd.initAdProperties(FullAd.element);
        AbstractAd.initTagCloud(FullAd.element);

        FullAd._initRelatedAds();

        // add click to tag link in "tag cloud" section
        FullAd.element.getElement(".tag-this-ad-cloud").addReplacingEvent("click", function(e) {
            AbstractAd._showTagForm(FullAd._currentOpenedAdId, this);
        });
        FullAdChicklets.init();
    },

    _initRelatedAds: function() {
        var container = $("fullad-related-ads-ad-container");
        // in case there are no related ads
        if (!container) return;
        var previous = container.getElement(".previous"),
			next = container.getElement(".next");
        var idx = 0, elements = container.getElements("li");

        function goTo() {
            $("related-ads-list").retrieveOrStore("fxScroll", function() {
                return new Fx.Scroll(this, { wheelStops: false, transition: Fx.Transitions.Expo.easeOut });
            }).toElement(elements[idx]);
        }

        previous.addReplacingEvent("click", function(e) {
            if (--idx < 0) idx = elements.length - 1;
            goTo();
        });
        next.addReplacingEvent("click", function(e) {
            if (++idx >= elements.length) idx = 0;
            goTo();
        });

        container.getElements(".ads>li").addReplacingEvent("click", function() {
            var adId = +this.id.split("-")[1]; // id in format ad-44
            FullAd.open(adId);
        });
    },

    _headerOpened: true,
    _headersHeight: null,
    _minimizeHeader: function() {

        if (!FullAd._headerOpened) return;

        FullAd._headersHeight = $("headers").scrollHeight;

        $("header-expand")
			.setVisibility(false)
			.show()

        FullAd._headersCollapsedHeight = $("header-expand").getStyle("height").toInt();

        $("header-collapse-wrap").setStyle("opacity", 0).show().retrieveOrStore("fx", function() {
            return this.effect("opacity", { wait: false });
        }).start(1);
        FullAd._initializeBackAndCloseButtons.callOnce();
        $("header-collapse-close").hide();

        // minimize the header div and raise it up until not seen
        if (!Browser.Engine.trident4) {
            $("headers")
            // set overflow:hidden, we're gonna change the height
				.setStyle("overflow", "hidden")
				.retrieveOrStore("minimizeFx", function() { return this.effects({ wait: false }); })
				.start({
				    top: -FullAd._headersHeight,
				    height: FullAd._headersCollapsedHeight - 12
				});
        } else {
            $("headers")
            // set overflow:hidden, we're gonna change the height
				.setStyles({
				    "overflow": "hidden",
				    top: -FullAd._headersHeight,
				    height: FullAd._headersCollapsedHeight - 12
				});
        }
        // lower the header-expand from top, which contains the open menu button
        if (!Browser.Engine.trident4) {
            $("header-expand")
				.setStyle("top", -FullAd._headersCollapsedHeight)
				.setVisibility(true)
				.retrieveOrStore("minimizeFx", function() {
				    return this.effect("top", { wait: false });
				}).start(0);
        } else {
            $("header-expand")
				.setStyle("top", 0)
				.setVisibility(true);
        }
        if (!$("header-expand").retrieve("restoreHeaderEvent")) {
            $("header-expand").getElement("a").setProperty("hideFocus", "hideFocus").addReplacingEvent("click", function(e) {
                FullAd._restoreHeader(true);
            });
            $("header-expand").store("restoreHeaderEvent", true);
        }

        FullAd._headerOpened = false;
        FullAdChicklets.init();

        return $("headers").retrieve("minimizeFx");
    },
    _restoreHeader: function(showBackAndCloseButtons) {
        if (FullAd._headerOpened) return;
        FullAd._headerOpened = true;

        if (!Browser.Engine.trident4) {
            $("header-expand").retrieve("minimizeFx").start(-FullAd._headersCollapsedHeight);
            $("headers")
            // restore overflow
            //.setStyles({overflow:""}) // remarked cause it doesn't work properly as for now
				.retrieve("minimizeFx")
				.setOptions({ duration: 500 })
				.start({ height: FullAd._headersHeight, top: 0 })
				.chain(function() {
				    if (showBackAndCloseButtons) {
				        // show close buttons
				        $("header-collapse-close").show();
				    }
				});
        }
        else {
            $("header-expand").setStyle("top", -FullAd._headersCollapsedHeight.toInt());
            $("headers").setStyles({ height: FullAd._headersHeight, top: 0 });
            if (showBackAndCloseButtons) {
                // show close buttons
                $("header-collapse-close").show();
            }
        }
        FullAdChicklets.init();
    },
    _initializeBackAndCloseButtons: function() {
        $("header-collapse-back").addReplacingEvent("click", function(e) {
            FullAd.close();
        });
        $("header-collapse-close").addReplacingEvent("click", function(e) {
            FullAd._minimizeHeader();
        });
        FullAdChicklets.init();
    },
    // restores header, hides the fullad and shows the ad list
    close: function() {
        if (!FullAd._isOpened) return;
        FullAd._isOpened = false;
        if ($("fullad-template")) $("fullad-template").src = "about:blank";
        FullAd._restoreHeader(false);
        if ($("header-collapse-wrap").retrieve("fx")) $("header-collapse-wrap").retrieve("fx").start(0);
        FullAd._currentOpenedAdId = null;
        FullAd._currentAdId = null;
        if (!Browser.Engine.trident4) {
            FullAd.element.retrieve("fxOpen").start({ opacity: 0, height: 0 })
				.chain(function() {
				    FullAd.element.empty();
				    Ads.showList.delay(50);
				});
        }
        else {
            FullAd.element.setStyles({ opacity: 0, height: 0 }).empty();
            Ads.showList.delay(50);
        }
    }
};
$DL(FullAd.init);


var FullAdComments={
	init:function () {
		FullAdComments.form=$("comments-form");

		FullAdComments.form.addReplacingEvent("submit",function (e) {
			if($('comments-HP').value != ''){
				FullAdComments.close();
				return;
			}
			Mantis.EyeBlaster.Services.CommentService.AddComment(
				FullAd._currentAdId,
				$("comments-UserName").value,
				$("comments-Email").value,
				$("comments-Body").value,
				function (source) {
					$("comment-container").setHTML(source);
					$("comments-Body").value="";
					// update number of comments
					$("fullad-button-comments-amount").set("text",$("comment-container").getElements("li").length);

					// scroll to and pulsate new comment
					var newComment=$("comment-container").getElement(".currentAdded");
					if(newComment){
						new Fx.Scroll(document.documentElement,{wheelStops:false,transition:Fx.Transitions.Expo.easeOut}).toElement(newComment)
					
						var fx=newComment.effect("opacity",{duration:150});
						function fadeIn() { return fx.start(1); }
						function fadeOut() { return fx.start(0); }

						fadeOut()
							.chain(fadeIn).chain(fadeOut).chain(fadeIn).chain(fadeOut)
							.chain(fadeIn).chain(fadeOut).chain(fadeIn).chain(fadeOut)
							.chain(fadeIn);
						}
					else{
					
						//new Fx.Scroll(document.documentElement,{wheelStops:false,transition:Fx.Transitions.Expo.easeOut}).toElement($("comment-container"))
					
					}
					
					FullAdComments.close();
				}
			);
		});
	},
	_isOpened:false,
	toggle:function () {
		if (FullAdComments._isOpened) FullAdComments.close(); else FullAdComments.open();
		FullAdComments._isOpened=!FullAdComments._isOpened;
	},
	open:function () {
		FullAdComments.init.callOnce();

		FullAdComments.form
			.setStyles({opacity:0,height:0})
			.show()
			
		var finalHeight=FullAdComments.form.scrollHeight;
		
		FullAdComments.form
			.retrieveOrStore("fx",function () {
				return this.effects({wait:false});
			})
			.start({opacity:1,height:finalHeight});
	},
	close:function () {
		FullAdComments.form.retrieve("fx").start({opacity:0,height:0});
	}
};

Events.makeObjectEventable(FullAd);

var FullAdChicklets={
    _timer:0,
	_isOpen:false,
	_isLoaded:false,
	init:function () {

		$waitUntil(function () {
				return (!!$E("#fullad .site-rss") && $chk('fulladgrab'));
			},function () {
				$E("#fullad .site-rss").addReplacingEvent("mouseenter",function (e) {
					FullAdChicklets._show();
					Site.trackStats("/GrabThisSite");
					this.addClass("site-rss-on");
				});
				$E("#fullad .site-rss").addReplacingEvent("mouseleave",function (e) {
					FullAdChicklets._prepareHide();
				});
				$("fulladgrab").addReplacingEvent("mouseenter",function (e) {
					FullAdChicklets._show();
				});
				$("fulladgrab").addReplacingEvent("mouseleave",function (e) {
					FullAdChicklets._prepareHide();
				});				
			});	
	},
		
	_show:function(){
		$clear(FullAdChicklets._timer);
        FullAdChicklets._timer=0;
		if(FullAdChicklets._isOpen) return;
		FullAdChicklets._isOpen=true;
		$("fulladgrab-placeholder").empty();
		FullAdChicklets.fx=$("fulladgrab-placeholder").get("tween",{
			property:"height",
			duration: 200,
			wait: false,			
			transition: Fx.Transitions.linear
		}).set(0).start(90);		
		$("fulladgrab").show();
		$("fulladgrab").setStyle("left", $("fullad").getElement("#fullad-buttons .site-rss").getCoordinates($("fullad")).left );//+ $("fulladgrab").getCoordinates().width
		
		if(!FullAdChicklets._isLoaded){
			Mantis.EyeBlaster.Services.ChickletsService.GetChickletsFormSource(function (source) {
				var el=new Element("div").adopt(Element.fromMarkup(source,true));			
				(function () {
					$("fulladgrab").removeClass("loading");
					$("fulladgrab-placeholder").adopt(el);
					FullAdChicklets.fx.start(90);
				}).delay(100);
			});
		}else{
			FullAdChicklets.fx.start(90);
		}
	},
	_hide:function(){
		FullAdChicklets.fx.set(0);
		FullAdChicklets._isOpen=false;
		$E("#fullad .site-rss").removeClass("site-rss-on");		
		$("fulladgrab").hide();
	},		
	_prepareHide:function(){
	    if (FullAdChicklets._timer==0)
	    FullAdChicklets._timer = setTimeout(FullAdChicklets._hide,300);//.delay(200);		
	}
};
$DL(FullAdChicklets.init);
