// 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 TopMenu = {
    _element: null,
    _newsletterLB: null,
    _loginLB: null,
    init: function() {
        $$("#top-menu li.menu-item").each(function(li, index) {
            var drop = li.getFirst(".drop");
            if (drop) {
                var height = drop.getElement("ul").getHeight() + 24;
                var width = drop.getWidth();
                drop.getElement(".bottom-mid").setStyles({ "width": width - 27 });
                drop.setStyles({ "overflow": "hidden", "height": 0 });

                li.addEvents({
                    mouseenter: function(e) {
                        e.stop();
                        //if(e.target!=li.getElement("a"))return;
                        drop.fx = new Fx.Morph(drop, { duration: 100, transition: Fx.Transitions.Sine.easeOut });
                        TopMenu.show(drop, height, width);
                    },
                    mouseleave: function(e) {
                        e.stop();
                        TopMenu.prepareHide(drop);
                    }
                });
            }
        });
        TopMenu._loadNewsletterSignUp();
        TopMenu._loadLogin();
    },
    show: function(drop, height, width) {
        $clear(TopMenu._timer);
        if (drop._isOpen) return;
        if (TopMenu._lastDrop == drop) return;
        if (TopMenu._lastDrop) TopMenu.hide(TopMenu._lastDrop);
        if (drop.fx) drop.fx.cancel();

        drop._isOpen = true;
        //*----ie7 problem with width---*/
        //		var li=drop.getElement("li");
        //		drop.getWidth()>150?li.setStyles({"width":drop.getWidth()}):li.setStyles({"width":150});		
        drop.setStyles({ "visibility": "visible" });

        drop.fx.start({ "height": [0, height - 10] }).chain(function() {
            drop.setStyles({ "overflow": "" });
        });
        TopMenu._lastDrop = drop;
    },
    hide: function(drop) {
        drop.setStyles({ "overflow": "hidden", "visibility": "hidden", "height": 0 });
        drop._isOpen = false;
        TopMenu._lastDrop = null;
        //new Fx.Morph(drop, {duration: 300, transition: Fx.Transitions.Sine.easeOut})
        //.start({"height":0}).chain(function(){			

        //});
    },
    prepareHide: function(drop) {
        TopMenu._timer = TopMenu.hide.bind(this, drop).delay(400);
    },

    _loadNewsletterSignUp: function() {
        TopMenu._newsletterLB = $('newsletter-popup');
        if (TopMenu._newsletterLB != null) {
            var ttl = TopMenu._newsletterLB.getElement(".title");
            Mantis.FormGenerator.FormGeneratorService.GetFormSource("Newsletter", null, function(source) {
                var form = Element.fromMarkup(source);
                $("newsletter-lightbox-content").empty().grab(form);
                if ($("newsletter-text")) { ttl.innerHTML = $("newsletter-text").innerHTML; }
            });
        }
    },
    _loadLogin: function() {
        TopMenu._loginLB = $('login-popup');
        if (TopMenu._loginLB != null) {
            var ttl = TopMenu._loginLB.getElement(".title");
            if ($("login-text")) { ttl.innerHTML = $("login-text").innerHTML; } 
        }
    }

};
$domready(TopMenu.init);


var registerConversion = function(account, label) {
    var image = new Image(1, 1);
    image.src = 'http://www.googleadservices.com/pagead/conversion/' + account + '/?label=' + label + '&amp;guid=ON&amp;script=0';
    return true;
};
var UserManager = (function() {
    //var _countriesLB;
    //var _languagesLB;
    function init() {

        $$(".user-login").addReplacingEvent("click", function(e) {
            UserManager.openLogin();
        });
        $$(".user-logout").addReplacingEvent("click", function(e) {
            UserManager.logout();
        });

        var sTextF = $("searchText");

        if (sTextF != null) {
            $("searchButton").addReplacingEvent("click", function(e) {
                UserManager.search(sTextF);
            });

            sTextF.addReplacingEvent("click", function(e) {
                if ((sTextF.value == "") || (sTextF.value == $("EnterKeyword").innerHTML)) {
                    sTextF.value = "";
                }
            });
            sTextF.addEvent("keypress", function(e) {
                if (e.key && !e.shift) switch (e.key) {
                    case "enter":
                        UserManager.search(sTextF);
                        return;
                }
            });
        }

        //setUpCountriesLB();

        if ($("languagesDD") != null) {
            $("languagesDD").hide();
            $("langs").addReplacingEvent('click', function() {
                $("languagesDD").show();
            });
        }
    }


    $domready(init);

    function setUpCountriesLB() {
        var tempId1;
        var tempId2;
        var countriesList = $("countries-lightbox").getElements(".country-link");
        var languagesList = $("languages-lightbox").getElements(".lang-link");
        UserManager._countriesLB = new Lightbox($("countries-lightbox"), { opacity: 0.5, backgroundColor: '#04234b', containerClass: '', hideOnEnter: false, hideOnEsc: false });
        UserManager._languagesLB = $("languages-lightbox");
        if (UserManager._languagesLB) {
            UserManager._languagesLB.hide();
            UserManager._languagesLB.getElements("ul").each(function(item, index) {
                item.hide();

                tempId1 = item.id.split("-")[0];
                item.getElement("a").addReplacingEvent("click", function(item) {
                    UserManager.setUpCookie(tempId1, item.id);
                });
            });
        }
        //		countriesList.each(function(item,index){
        //			item.addReplacingEvent("click",function(){
        //				setUpCurrentCountry(item);
        //			});
        //		});

        //make check if country + language was selected:
        //if not - show LB & save in cookie;
        var currCountry = UserManager._get_cookie("country");
        var currLang = UserManager._get_cookie("language");

        //if no cookie & more then 1 site is online
        if ((countriesList.length > 1) && (languagesList.length > 1) && ((!currCountry) || (!currLang))) {
            UserManager._countriesLB.show();
        }

        //else
        //retrive from cookie

        $("languagesDD").getElements("li").each(function(item) {
            tempId1 = item.id.split("-")[0];
            item.getElement("a").addReplacingEvent("click", function() {
                tempId2 = this.id.split("-")[0];
                UserManager.setUpCookie2(tempId1, tempId2);
            });
        });

    }

    function setUpCurrentCountry(t) {
        UserManager._languagesLB.hide();
        countriesList.each(function(item, index) {
            item.removeClass("on");
            if (item.id + "-code") $(item.id + "-code").hide();
        });
        t.addClass("on");
        if (t.id + "-code") {
            UserManager._languagesLB.setStyle("top", t.offsetTop + 25 + "px");
            $(t.id + "-code").show();
            UserManager._languagesLB.show();
        }

    }

    function loginLoaded() {
        new Lightbox(UserManager._loginFormElement).show();
    }


    return {
        openLogin: function() {
            // if already got source
            if (UserManager._loginFormElement) loginLoaded();
            // otherwise fetch source from server
            else Mantis.Web.Services.UserService.GetLoginFormSource(function(source) {
                UserManager._loginFormElement = Element.fromMarkup(source);
                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);
            });
        },
        search: function(textField) {
            var sText = textField;

            if ((sText.value == "") || (sText.value == $("EnterKeyword").innerHTML)) {
                sText.value = $("EnterKeyword").innerHTML;
            }
            else {
                //alert(Config.siteUrl + "search-results.aspx?" + escape(sText.value));
                location.href = Config.siteUrl + "search-results/" + escape(sText.value);
            }
        },

        _get_cookie: function(cookie_name) {
            var results = document.cookie.match('(^|;) ?' + cookie_name + '=([^;]*)(;|$)');
            if (results)
                return (unescape(results[2]));
            else
                return null;
        }
		,
        setUpCookie: function(country, language) {
            var currCountry = UserManager._get_cookie("country");
            var currLang = UserManager._get_cookie("language");
            if ((currCountry != country) || (currLang != language)) {
                var dateIt = new Date("January 1, 2030");
                var expires = "expires=" + dateIt.toGMTString();
                document.cookie = "country=" + country + ";" + expires + "; ";
                document.cookie = "language=" + language + ";" + expires + "; ";
            }

            if (UserManager._languagesLB) UserManager._languagesLB.hide();
            if (Lightbox != null) Lightbox.hide();

            location.href = location.href; //TODO:don't work;\
        },
        setUpCookie2: function(country, language) {
            //alert(country+"---"+language);
            var currCountry = UserManager._get_cookie("country");
            var currLang = UserManager._get_cookie("language");
            if ((currCountry != country) || (currLang != language)) {
                var dateIt = new Date("January 1, 2030");
                var expires = "expires=" + dateIt.toGMTString();
                document.cookie = "country=" + country + ";" + expires + "; ";
                document.cookie = "language=" + language + ";" + expires + "; ";
            }
            $("languagesDD").hide();
            location.href = location.href; //TODO:don't work;\
        }

    }
})();



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
*/
