// web service class to communicate with .asmx files with json
var WebService=new Class({
	Implements:[Chain,Options,Events],
	request:null,
	initialize:function (options) {
		this.setOptions(options);
	},
	send:function (methodName,data,onSuccess,onFailure) {
		this.request=new Request.JSON({
			url:this.url+"/"+methodName,
			onSuccess:function (response) {
				// .d property is of .net 3.5 stuff
				if ($type(response)=="object" && response.d!==undefined) response=response.d;
				if (onSuccess) onSuccess.call(this,response);
			},
			onFailure:function (ex) {
				var error=eval("("+ex.responseText+")").Message;
				if (onFailure) onFailure.call(this,error);
				else alert(error);
			}.bind(this),
			data:JSON.encode(data || {}),
			urlEncoded:false
		});
		this.request.headers
			.erase("Accept")
			.erase("X-Request")
			.extend({"Ajax-Call":true})
			.extend({"Requested-Site":Config.site})
			.extend({"Requested-Language":Config.language})
			.extend({"Content-Type":"application/json; charset=utf-8"});

		var e={cancel:false};
		WebService.fireEvent("onSending",[this.request,methodName,e]);
		if (e.cancel) return this;
		this.fireEvent("onSending",[this.request,methodName,e]);
		if (e.cancel) return this;
		this.request.send();
		this.fireEvent("onSent",[this.request,methodName,e]);
		WebService.fireEvent("onSent",[this.request,methodName,e]);

		return this;
	},
	abort:function () {
		if (this.request) this.request.cancel();

		return this;
	}
});
Events.makeObjectEventable(WebService);
/*
WebService.addEvents({
	onSending:function (request,methodName) {
		request.headers.extend({"I-Am-A":"Custom Header"});
		request.options.url="i-am-a-custom.url";
	},
	onSent:function (request,methodName) {
	}
});
*/

//WebService.addEvents({
//	onSending:function (request,methodName) {
//		if(request.headers){
//			
//		}
//	},
//	onSent:function (request,methodName) {
//	}
//});

$domready(function () {
	WebService.AuthenticationServiceClass=new Class({
		Extends:WebService,
		url:Config.rootUrl+"Authentication_JSON_AppService.axd",
		login:function (userName,password,createPersistentCookie,onSuccess,onFailure) {
			return WebService.prototype.send.apply(
				WebService.AuthenticationService,
				[
					"Login",
					{userName:userName,password:password,createPersistentCookie:createPersistentCookie},
					onSuccess,
					onFailure
				]
			);
		},
		logout:function (redirectUrl,onSuccess,onFailure) {
			return WebService.prototype.send.apply(
				WebService.AuthenticationService,
				[
					"Logout",
					null,
					onSuccess ? onSuccess.bind(null,[redirectUrl]) : function (redirectUrl) {
						// if no redirectUrl supplied - location.href=self will reload the page (without submitting forms if were)
						location.href=redirectUrl || location.href;
					},
					onFailure
				]
			);
		}
	});
	WebService.AuthenticationService=new WebService.AuthenticationServiceClass();

	WebService.ProfileServiceClass=new Class({
		Extends:WebService,
		url:Config.rootUrl+"Profile_JSON_AppService.axd",
		properties:new Hash(),
		save:function (propertyNamesToSave,onSuccess,onFailure) {
			var propertiesWithValues={};
			propertyNamesToSave.each(function (name) {
				propertiesWithValues[name]=this.properties[name];
			},this);
			return WebService.prototype.send.apply(
				WebService.ProfileService,
				[
					"SetPropertiesForCurrentUser",
					{values:propertiesWithValues,authenticatedUserOnly:false},
					onSuccess,
					onFailure
				]
			);
		},
		load:function (propertyNamesToLoad,onSuccess,onFailure) {
			var methodName,args=new Hash();

			if (!propertyNamesToLoad) {
				methodName="GetAllPropertiesForCurrentUser";
			} else {
				methodName="GetPropertiesForCurrentUser";
				propertyNamesToLoad.removeDuplicates();
				args.extend({properties:propertyNamesToLoad});
			}
			args.extend({authenticatedUserOnly:false});

			return WebService.prototype.send.apply(
				WebService.ProfileService,
				[
					methodName,
					args,
					function (result) {
						Hash.each(result,function (value,key) {
							this.properties[key]=value;
						},this);
						
						if (onSuccess) onSuccess(result);
					}.bind(this),
					onFailure
				]
			);
		}
	});
	WebService.ProfileService=new WebService.ProfileServiceClass();
},2);

var Tracker={
	track:function (url) {		
		//if(pageTracker!="undefined")pageTracker._trackPageview(url);
		//alert($defined(pageTracker));
	}	
};

var SideMenu={
	origImage:null,
	init:function(){
		var imageUrl="/images/mainmenu/{img}.png";
		$$("#side-menu li div").addEvents({
			'mouseenter': function(){
				var img=this.getElement("img");
				if(img==null) return;
				if(img.get("src").indexOf("current")>-1) return;
				SideMenu.origImage=img.get("src");
				img.set("src",imageUrl.replace("{img}",img.get("id")+"-over"));
			},
			'mouseleave': function(){
				var img=this.getElement("img");
				if(img==null) return;
				if(img.get("src").indexOf("current")>-1) return;
				this.getElement("img").set("src",SideMenu.origImage);
			}
		});
	}
};

$domready(SideMenu.init);




var UserManager={
	init:function() {
		if($("footer-client-zone") && !UserManager.isLogIn){
			$("footer-client-zone").addReplacingEvent("click",function (e) {
				UserManager.openLogin();
			});
		}
		if($("user-logout")){
			$("user-logout").addReplacingEvent("click",function (e) {
				UserManager.logout();
			});
		}
	},

	loginLoaded:function() {
		var top=$("footer-client-zone").getTop()-214;
		var lb = new Lightbox(UserManager._loginFormElement,{opacity:0.4,hideOnEnter:false,hideOnEsc:true,fixedTop:top,contentClass:"login-lightbox-content"});
		lb.show();
		UserManager._loginFormElement.getElement(".close").addEvent("click",function(e) {
			Login.clearMessages();
			lb.hide();
		});
	},

	openLogin:function () {
		// if already got source
		if (UserManager._loginFormElement) UserManager.loginLoaded();
		// otherwise fetch source from server
		else Mantis.Web.Services.UserService.GetLoginFormSource(function (source) {
			UserManager._loginFormElement=Element.fromMarkup(source);
			UserManager.loginLoaded();
		});
	},
	openResetPassword:function () {
		UserManager.openLogin();
	},
	logout:function () {
		WebService.AuthenticationService.logout();
	},
	sendPassword:function (userName,callback) {
		Mantis.Web.Services.UserService.SendPassword(userName,function (success) {
			if (callback) callback(success);
		});
	}
};

$domready(UserManager.init);


var Lightbox=new Class({
	Implements:[Options,Events],

	_element:null,
	options:{
		overlayClass:"lightbox-overlay",
		containerClass:"lightbox-container",
		contentClass:"lightbox-content",
		hideOnEnter:true,
		hideOnEsc:true,
		opacity:0.4,
		fixedTop: false,
		reposition: true,
		onBeforeShow:$empty,
		onAfterShow:$empty,
		onBeforeHide:$empty,
		onAfterHide:$empty
	},

	initialize:function (element,options) {
		this._element=element;
		this._elementOldParent=element.getParent();
		if (this._elementOldParent) this._hiddenAtFirst=!element.get("display");
		this.setOptions(options);
	},

	show:function () {
		if (Lightbox.current) Lightbox._hide();
		Lightbox.current=this;

		this.fireEvent("onBeforeShow");
		Lightbox._show(this._element,this.options);
		this.fireEvent("onAfterShow");
	},
	hide:function () {
		this.fireEvent("onBeforeHide");
		Lightbox._hide();
		this.fireEvent("onAfterHide");
	}
});

// static methods/properties
$extend(Lightbox, {
    overlay: null,
    container: null,
    reposition: true,
    _init: function(options) {
        if (!Lightbox.overlay) {
            Lightbox.overlay = new Element("div").inject(document.body).set({
                styles: {
                    backgroundColor: options.backgroundColor || "#000",
                    // ie6 doesn't support position:fixed
                    position: Browser.Engine.trident4 ? "absolute" : "fixed",
                    top: 0,
                    left: 0,
                    zIndex: 1000
                },
                opacity: options.opacity,
                display: false
            });
        }
        else Lightbox.overlay.className = "";
        reposition = options.reposition;
        Lightbox.overlay.addClass(options.overlayClass);

        if (!Lightbox.container) {
            Lightbox.container = new Element("div").inject(document.body).set({
                styles: {
                    // ie6 doesn't support position:fixed
                    position: options.fixed ? "fixed" : "absolute",
                    top: 0,
                    left: 0,
                    zIndex: 1001
                },
                display: false
            });
        }
        else Lightbox.container.className = "";
        Lightbox.container.addClass(options.containerClass);

        if (!Lightbox._fix) Lightbox._fix = new OverlayFix(Lightbox.overlay);
    },

    _onScroll: function() {
        if (!Lightbox.current) removeEvent("scroll", arguments.callee);
        // since ie6 doesn't support position:fixed we need to take care of re-position overlay and container when scrolling
        if (reposition)
            Lightbox.adjustPositions();
    },
    _onResize: function() {
        if (!Lightbox.current) removeEvent("resize", arguments.callee);
        // re define the w/h of the overlay if the page's w/h has changed
        Lightbox._setOverlayHeight();
        if (reposition)
            Lightbox.adjustPositions();
    },
    _setOverlayHeight: function() {
        var size = document.getSize();
        Lightbox.overlay.setStyles({
            width: size.x,
            height: size.y
        });
    },

    _show: function(element, options) {
        Lightbox._init(options);

        Lightbox.fireEvent("onBeforeShow");

        element.set({
            visibility: false,
            display: true
        });

        Lightbox.overlay.show();
        Lightbox.container.show();

        Lightbox._fix.show();

        Lightbox.container.empty().adopt(new Element("div").addClass(options.contentClass).adopt(element));

        // keep set them when resizing
        addEvent("resize", Lightbox._onResize.bind(this));
        Lightbox._setOverlayHeight();
        //if (Browser.Engine.trident4) addEvent("scroll",Lightbox._onScroll);

        Lightbox.adjustPositions();
        if (options.reposition)
            Lightbox.adjustPositionsInterval = Lightbox.adjustPositions.periodical(300);

        element.set("visibility", true);

        Lightbox.fireEvent("onAfterShow");
        var lightboxKeydown = $(document.documentElement).retrieveOrStore("lightboxKeydown", function() {
            return function(e) {
                if (["input", "textarea", "select"].contains(Element.get(e.target, "tag"))) return;
                switch (e.key) {
                    case "esc":
                        Lightbox.fireEvent("onEsc", e); // e could be extended with cancel=true and lightbox won't get closed!
                        Lightbox.current.fireEvent("onEsc", e);
                        if (options.hideOnEsc && !e.cancel) Lightbox._hide();
                        break;
                    case "enter":
                        Lightbox.fireEvent("onEnter", e);
                        Lightbox.current.fireEvent("onEnter", e);
                        if (options.hideOnEnter && !e.cancel) Lightbox._hide();
                        break;
                }
            };
        });
        $(document.documentElement).addEvent("keydown", lightboxKeydown);
    },

    _hide: function() {
        Lightbox.fireEvent("onBeforeHide");

        Lightbox.overlay.set("display", false);
        Lightbox.container.set("display", false);

        Lightbox.adjustPositionsInterval = $clear(Lightbox.adjustPositionsInterval);

        Lightbox._fix.hide();

        $(document.documentElement).removeEvent("keydown", $(document.documentElement).retrieve("lightboxKeydown"));

        Lightbox.fireEvent("onAfterHide");

        if (Lightbox.current) {
            if (Lightbox.current._hiddenAtFirst) Lightbox.current._element.set("display", false);
            // re place the element in its original parent if any
            if (Lightbox.current._elementOldParent) Lightbox.current._elementOldParent.adopt(Lightbox.current._element);
        }

        Lightbox.current = null;
    },

    hide: function() {
        Lightbox._hide();
    },

    adjustPositions: function() {
        if (!Lightbox.current) return;

        var element = Lightbox.current._element,
			options = Lightbox.current.options;

        // TODO: allow fixed top

        var scrollTop = document.getScroll().y;

        var pos = {};
        pos.x = (document.getSize().x - element.offsetWidth) / 2;
        //pos.y=options.fixedTop ? options.fixedTop : document.getScroll().y+(document.getSize().y-element.offsetHeight)/2;
        pos.y = options.fixedTop ? options.fixedTop : scrollTop + (document.getSize().y - element.offsetHeight) / 2;

        pos.x = Math.max(0, pos.x);
        pos.y = Math.max(0, pos.y);

        // ie6 doesn't support fixed position so we have to update the lightbox overlay manually
        if (Browser.Engine.trident4) Lightbox.overlay.setStyle("top", scrollTop);

        Lightbox.fireEvent("onPositioning", [Lightbox.container, pos]);

        Lightbox.container.position(pos);

        Lightbox._fix.show();
    }
});
Events.makeObjectEventable(Lightbox);
Options.makeClassOptionable(Lightbox);

/*
-- js
var lb=new Lightbox(element);
lb.show();

lb.hide();
or Lightbox.hide();

Lightbox
*/
