// Sticking jQuery into it's own namespace while Moo stuff is used.

if (typeof(jQuery) != "undefined") {
    jQuery.noConflict();
}

// Class to create, show and hide the grey backing when showing a pop-up
var GreyScreen = new Class({

    initialize: function() {
        this.greyDiv = new Element("div",{
            id: "greydiv",
            styles: {
                "opacity": 0,
                "top": 0,
                "left": 0,
                "background-color": "#000000",
                "position": "fixed",
                "height": "100%",
                "width": "100%",
				"z-index": 100
            }
        });
        BrowserFix.fixElement(this.greyDiv);
        this.greyDiv.set('morph', {duration: '300'});
        $(document.body).adopt(this.greyDiv);
    },
    show: function(opts) {
        this.greyDiv.setStyle("display","block");
        this.greyDiv.morph({
            "opacity": 0.8
        });
        if (opts && opts.onComplete) {
            opts.onComplete.delay(300);
        }
        if (BrowserFix.isIE6) {
            $$('select').setStyle("visibility","hidden");
        }
    },
    hide: function() {
        if (this.greyDiv) {
            this.greyDiv.setStyles({
                "display":"none",
                "opacity": 0
            });
        }
        if (BrowserFix.isIE6) {
            $$('select').setStyle("visibility","visible");
        }
    },
    dispose: function() {
        this.greyDiv.dispose();
    }
});



var BrowserFix = new new Class({
    // Class to handle browser-specific issues. At the moment it only does position: fixed stuff, but will do more.
    //
    // It also has a variable called isIE6, which is a boolean value that can be used anywhere to detect whether
    // we're running on the devil's browser or not.
	//
	// The "new new" initializer above looks weird, but it's basically making BrowserFix the javascript equivalent of
	// a C# static class- you never need to make an instance of it.
    
    initialize: function() {
        if (Browser.Engine.version == 4 && Browser.Engine.trident) {
            this.isIE6 = true;
			this.fixedPosHack = false;	
        } else {
            this.isIE6 = false;
        }
        if (Browser.Engine.version == 5 && Browser.Engine.trident) {
            this.isIE7 = true;
        } else {
            this.isIE7 = false;
        }
    },
    fixElement: function(el) {
		// This is very simple right now, but could get a lot more complicated if we start looking at 32-bit PNG fixes, etc.
        if (this.isIE6) {
			if (this.fixedPosHack == false) {
				this.doFixedPosHack();
			}
			if (el.getStyle("position") == "fixed") {
				el.setStyle("position", "absolute");
				if (el.getStyle("top").indexOf("px") > -1) {
				    el.style.setExpression("top","window.getScroll().y + " + el.getStyle("top").toInt());
				} else if (el.getStyle("top").indexOf("%") > -1) {
                    var extra = Math.round(window.getSize().y * (parseInt(el.getStyle("top").replace("%","")) / 100));
                   el.setStyle("top",window.getScroll().y + extra);
                   // this should work but appears not to consistently?
                  el.style.setExpression("top",'(window.getScroll().y + ' + extra + '))');

				}
			}
			if (el.getStyle("height").indexOf("%") > -1) {
			    var factor = parseInt(el.getStyle("height").replace("%","") ) / 100;
			    el.setStyle("height",window.getSize().y * factor);
			    el.style.setExpression('(\
                    Math.round(\
                    (window.getSize().y) * \
                    '+ factor + ' \
                    ))');
                    
			    
			}
		}
	},
	doFixedPosHack: function() {
		// CSS hack to allow fixed positioning in IE6. This seems too simple, and I'm convinced it'll break something horribly.
		
		/*$$('html, body').setStyles({
			height: "100%",
			overflow: "auto"
		});*/
		
		this.fixedPosHack = true;
	},
	
	giveBorderRadius: function(element, value, vert, horiz) {
		var name = "";
		if (Browser.Engine.gecko) {
			if (horiz == null && vert == null) {
				name = "-moz-border-radius";
			} else {
				name = "-moz-border-radius-" + vert + horiz;
			}
		} else if (Browser.Engine.webkit) {
			if (horiz == null && vert == null) {
				name = "-webkit-border-radius";
			} else {
				name = "-webkit-border-" + vert + "-" + horiz + "-radius";
			}
		} else {
			if (horiz == null && vert == null) {
				name = "border-radius";
			} else {
				name = "border-" + vert + "-" + horiz + "-radius";
			}
		}
		element.setStyle(name,value);
	}
});


var ImageDisplayer = new Class({
    initialize: function(target, json, showGreyScreen) {
       if (showGreyScreen == null || showGreyScreen == true) {
            this.showGreyScreen = true;
       } else {
            this.showGreyScreen = false;
       }
       this.targetLinks = target.getChildren("a");
       if (this.targetLinks.length > 0 && this.targetLinks[0].get("href") != null && this.targetLinks[0].get("href") != "" ) {
           this.listingCode = /listing=(.*)&picture=/.exec(this.targetLinks[0].get("href"))[1];
	       this.images = json;
	       this.targetLinks.addEvent("click",this.linkClick.bind(this));
        }	   
    },
	linkClick: function(e){
		e.stop();
		var thisLink = $(e.target);
		//alert(e.target.tagName)
		while (thisLink.tagName.toLowerCase() != "a") {
			thisLink = thisLink.getParent();
			
		}
		thisLink.blur();
		this.selectedIndex = this.targetLinks.indexOf(thisLink);
		this.imageWindow= new imageWindowHandler(this);
		/*if (this.showGreyScreen) {
		    this.greyScreen = new GreyScreen();
		    this.greyScreen.show({
			    onComplete: this.imageWindow.show.bind(this.imageWindow)
		    });
		} else {*/
		    this.imageWindow.show();
		//}
	},
	activeImage: function() {
		return this.images[this.selectedIndex];
	},
	disposeImageWindow: function() {
		this.imageWindow.dispose();
		if (this.showGreyScreen) {
		    this.greyScreen.hide();
		    //this.greyScreen.dispose();
		    this.greyScreen = null;
		}
		this.imageWindow = null;
	}
	,trackView: function() {
		if (typeof(pageTracker) != "undefined") {
			pageTracker._trackPageview(this.targetLinks[this.selectedIndex].get("href")); 
		}
	}
	
	
});

var SingleImageDisplayer = new Class({
    initialize: function(target, json) {
       this.targetLink = $(target);
	   /*var linktext;
		linktext = "/" + this.targetLink.get("rel").replace("thumbToFull:","");*/
       this.image = {
			"imageurl" :  this.targetLink.get("rel").replace("thumbToFull:","")
		};
	   this.selectedIndex = 0;
	   this.targetLink.addEvent("click",this.linkClick.bind(this));
    },
	linkClick: function(e){
		e.stop();
		this.targetLink.blur();
		
		this.imageWindow= new imageWindowHandler(this);
		this.greyScreen = new GreyScreen();
		this.greyScreen.show({
			onComplete: this.imageWindow.show.bind(this.imageWindow)
		});
	},
	activeImage: function() {
		return this.image;
	},
	disposeImageWindow: function() {
		this.imageWindow.dispose();
		this.greyScreen.hide();
		//this.greyScreen.dispose();
		this.greyScreen = null;
		this.imageWindow = null;
	}
	,trackView: function() {
		if (pageTracker) {
			pageTracker._trackPageview(this.targetLink.get("href")); 
		}
	}
	
	
});




var imageWindowHandler = new Class({
		initialize: function(parent) {
			this.parent = parent;
			this.div = null;
		},
		makeBox: function() {
			/*this.div = new Element("div", {
				id: "imageWindow",
				styles: {
					"width": "80%",
					"height": "80%",
					"position": "fixed",
					"top": "10%",
					"left": "10%",
					"display": "none",
					"background": "#ffffff",
					"z-index": 11001
					
				}
			});
			BrowserFix.giveBorderRadius(this.div,"10px");
			*/
			this.popupWindow = new StickyWin.Modal({
                showNow: false,
                inject: {target: $('aspnetForm'), where:'bottom'},
                closeOnClickOut: true,
                width: window.getSize().x * 0.8,
                height: window.getSize().y * 0.8
            });
            this.popupWindow.element.set('morph', {duration: 'long', transition: 'sine:out'});
			this.div = ErmJS.Controls.popUpWindow({
			    fillSpace: true,
			    usePadding: false,
			    parentWindow: this.popupWindow
			 });
			this.popupWindow.setContent(this.div);
			this.containerDiv = new Element("div", {
				styles: {
					"position": "relative",
					"height": "100%",
					"width": "100%"
					
				},
				id: "imageWindow"
			});
			this.div = this.div.getFirst();
			this.div.adopt(this.containerDiv);
			// BrowserFix.fixElement(this.div);
			 
			 
			 
			 
			this.sidebarDiv = new Element("div", {
				styles: {
					"position": "absolute",
					"height": "100%",
					"width": "95px",
					"background-color": "#cccccc",
					
					"top": "0px",
					"right": "0px",
					"z-index": "101",
					"overflow":"hidden"
				}
			});
			
			
			
			// There's a lot of position issues so we end up making a huge loads of DIV tags
			this.imageContainerDiv = new Element("div", {
				styles: {
					"height": "100%",
					"position": "relative",
					"margin-right": "95px"
					
				}
			});
			
			this.imageContainerDiv.addEvent("mousewheel", function(e) {
			    if (this.sidebarDiv.getStyle("overflow") == "auto") {
			        if (e.wheel == 1) {
			            this.sidebarDiv.scrollTo(0,this.sidebarDiv.getScroll().y - 86)
			        } else {
			            this.sidebarDiv.scrollTo(0,this.sidebarDiv.getScroll().y + 86)
			        }
			    }
			    e.stop();
			    
			    }.bind(this));
			
			
			
			this.imageBoxContainerDiv = new Element("div", {
				styles: {
					"position": "relative",
					"height": "100%",
					"width": "100%"
					
				}
			});
			this.imageBoxDiv = new Element("div", {
				styles: {
					"position": "absolute",
					"border": "solid 1px black",
					"overflow": "hidden",
					"display": "none"
				}
			});
			this.controlDiv = new Element("div", {
				styles: {
					"position": "relative",
					"width": "100%",
					"height": "100%"
				}
			});
			
			this.controlBox = new Element("div", {
				styles: {
					"position": "absolute",
					"width": "30px",
					"height": "80px",
					"top": 0,
					"right": -51,
					"z-index": 500,
					"background": "#ffffff",
					"opacity": "0.7",
					"border": "solid 1px #888888",
					"border-width": "0px 0px 1px 1px",
					"padding": 10
					
				}
			});
			
			this.controlBox.set('morph', {duration: '600', transition: Fx.Transitions.Sine.easeOut});
			
			
			this.controlDiv.adopt(this.controlBox);
			this.plusSign = new Element("div",{
				styles:{
					background: "url(/content/common/images/magnify-plus.gif) no-repeat",
					height: 30,
					width: 30,
					opacity: 0.3,
					"margin-bottom": "20px"
				},
				events: {
					click: function() {
						if (this.plusSign.getStyle("opacity") == 1) {
							this.plusSign.setStyles({
								opacity: 0.3,
								cursor: "default"
							})
							this.minusSign.setStyles({
								opacity: 1,
								cursor: "pointer"
							})
							this.resizeBigImage();
						}
					}.bind(this)
				}
			});
			this.minusSign = new Element("div",{
				styles:{
					background: "url(/content/common/images/magnify-minus.gif) no-repeat",
					height: 30,
					width: 30,
					cursor: "pointer"
				},
				events: {
					click: function() {
						if (this.minusSign.getStyle("opacity") == 1) {
							this.minusSign.setStyles({
								opacity: 0.3,
								cursor: "default"
							});
							this.plusSign.setStyles({
								opacity: 1,
								cursor: "pointer"
							});
							this.resizeBigImage();
						}
					}.bind(this)
				}
			});
			this.controlBox.adopt(this.plusSign)
			this.controlBox.adopt(this.minusSign)
			
			
			
			this.imageBoxDiv.adopt(this.controlDiv);
			this.loadingBox = new Element("div", {
				"id": "loadingBox"
			});
			
			this.imageBoxContainerDiv.adopt(this.loadingBox);
			this.imageBoxContainerDiv.adopt(this.imageBoxDiv);
			this.imageContainerDiv.adopt(this.imageBoxContainerDiv);
			this.containerDiv.adopt(this.sidebarDiv);
			this.containerDiv.adopt(this.imageContainerDiv);
			this.imagesList = new Element("ul");
			this.sidebarDiv.adopt(this.imagesList);
			if (this.parent.images) {
				for (x = 0; x < this.parent.images.length; x++) {
					this.parent.images[x].imageObj = new Element("img", {
						src: unescape(this.parent.images[x].smallthumburl),
						height: 66,
						width: 66,
						events: {
							click: this.clickAction.bind(this)
						}
					});
					var liObj = new Element("li").adopt(this.parent.images[x].imageObj);
					if (this.parent.selectedIndex == x) {
						if (BrowserFix.isIE6) {
							liObj.addClass("activeie6");
						}
						else {
							liObj.addClass("active");
						}
					}
					this.imagesList.adopt(liObj);
				}
			} else {
				this.sidebarDiv.setStyle("display", "none");
				this.imageContainerDiv.setStyle("margin-left","0");
			}
			//IE 6 is useless, so we have to redesign the page slightly to take it into account
			
			if (BrowserFix.isIE6) {
				/*this.sidebarDiv.setStyles({
					"background": "#ffffff",
					"border": "none"
				});
				this.sidebarDiv.getElements("li").addClass("ie6");*/
			}
			
			
			
			this.div.set('morph', {duration: '300'});
			//$(document.body).adopt(this.div);
			
		},
		show: function() {

			if (this.div == null) {
			   
				this.makeBox();
			};
			/*this.div.setStyles({
				"opacity": 0,
				"display": "block"
			});
			
			this.div.morph({
				opacity: 1
			});*/
			this.popupWindow.show();
			this.popupWindow.pin();
			if (this.sidebarDiv.getScrollSize().y > this.sidebarDiv.getSize().y) {
			    this.sidebarDiv.setStyles({
			        "width": "110px",
			        "overflow":"auto"
			        });
			    if ($(document.body).hasClass("ie")) {
			        this.sidebarDiv.setStyle("overflow-x","hidden");
			     }
			    this.imageContainerDiv.setStyle("margin-right", "110px");
			    var active = this.sidebarDiv.getElement("li.active");
			    if (active.getPosition(active.getOffsetParent()).y + active.getSize().y > active.getOffsetParent().getSize().y) {
			        active.getOffsetParent().scrollTo(0,active.getPosition(active.getOffsetParent()).y);
			    }
			} else {
			     this.sidebarDiv.setStyles({
			        "width": "95px",
			        "overflow":"hidden"
			        });
			     
			     this.imageContainerDiv.setStyle("margin-right", "95px");
			     this.sidebarDiv.getFirst("ul").setStyle("height",this.sidebarDiv.getSize().y);
			}
			this.changeImage.bind(this).delay(300);
			this.resizeAction = this.displayImage.bind(this);
			window.addEvent("resize",this.resizeAction)
		},
		
		clickAction: function(e) {			
			for (x = 0; x < this.parent.images.length; x++) {
				if (this.parent.images[x].imageObj == e.target) {
					if (BrowserFix.isIE6) {
						this.parent.images[x].imageObj.getParent().addClass("activeie6");
					} else {
						this.parent.images[x].imageObj.getParent().addClass("active");
					}
					this.parent.selectedIndex = x;
					this.changeImage();
				} else {
					if (BrowserFix.isIE6) {
						this.parent.images[x].imageObj.getParent().removeClass("activeie6");
					} else {
						this.parent.images[x].imageObj.getParent().removeClass("active");
					}
				}
			}
		},
		changeImage: function() {
			this.controlBoxHasSlid = false;
			this.controlDiv.getChildren("img").dispose();
			this.parent.trackView();

			
			
			if (this.parent.activeImage().fullImageObj == null) {
				this.imageBoxDiv.setStyle("display","none");
				this.loadingBox.setStyle("display", "block");
				
				this.parent.activeImage().fullImageObj = new Asset.image(this.parent.activeImage().imageurl, {
					onload: this.displayImage.bind(this)
				})
			} else {
				this.displayImage();
			}
		},
		displayImage: function(disableAutomaticResize) {
			this.controlBox.setStyle("right", -51);
			if (this.imageBoxDiv.getStyle("display") == "none") {
				this.imageBoxDiv.setStyle("display","block");
				this.loadingBox.setStyle("display", "none");
			}
			this.controlDiv.adopt(this.parent.activeImage().fullImageObj);
			this.imageBoxDiv.adopt(this.controlDiv);
			if (this.isImageBiggerThanBox(this.parent.activeImage().fullImageObj) == false)
			{
				this.imageBoxDiv.setStyles({
					"top": "50%",
					"left": "50%",
					"margin-left": 0 - Math.round(this.parent.activeImage().fullImageObj.get("width") / 2),
					"margin-top": 0 - Math.round(this.parent.activeImage().fullImageObj.get("height") / 2),
					"width": this.parent.activeImage().fullImageObj.get("width") + "px",
					"height": this.parent.activeImage().fullImageObj.get("height") + "px"
				});
				
				
				// In case we're resizing the image after it's been dragged
				this.parent.activeImage().fullImageObj.setStyles({
					top: 0,
					left: 0
				})
				this.makeDraggableImage(false);
				if (this.parent.activeImage().fullImageObj.retrieve("origSize") == null) {
					this.controlBox.setStyle("right", -51);
				} else {
					this.controlBoxToggle();
				}
			} else {
				if (disableAutomaticResize != true) {
					this.resizeBigImage();
					return false;
				}
				// Even if it's bigger, we need to know if it's wider, taller or both.
				// Height
				if (this.parent.activeImage().fullImageObj.get("width") > (this.imageBoxContainerDiv.getSize().x - 20)) {
					this.imageBoxDiv.setStyles({
						"width": this.imageBoxContainerDiv.getSize().x - 40 + "px",
						"left": "20px",
						"margin-left": 0
					});
				} else {
					this.imageBoxDiv.setStyles({
						"width": this.parent.activeImage().fullImageObj.get("width") + "px",
						"left": "50%",
						"margin-left": 0 - Math.round(this.parent.activeImage().fullImageObj.get("width")/2) + "px"
					});
				}
				// Width
				
				if (this.parent.activeImage().fullImageObj.get("height") > (this.imageBoxContainerDiv.getSize().y - 20)) {
				    
					this.imageBoxDiv.setStyles({
						"height": this.imageBoxContainerDiv.getSize().y - 40 + "px",
						"top": "20px",
						"margin-top": 0
					})
				} else {
					this.imageBoxDiv.setStyles({
						"height": this.parent.activeImage().fullImageObj.get("height") + "px",
						"top": "50%",
						"margin-left": 0 - Math.round(this.parent.activeImage().fullImageObj.get("height")/2) + "px"
					});
				}
				this.imageBoxDiv.setStyle("overflow","hidden");
				this.parent.activeImage().fullImageObj.set("morph",{
								duration: 500,
								transition: Fx.Transitions.Circ.easeOut,
								onComplete: function(){
									
									this.element.store("morphInProgress",null)
								}
							});
				this.makeDraggableImage(true);
				this.controlBoxToggle();
			}

			/*new Fx.Morph(this.popupWindow.element,{duration:200}).start({
			    width: this.imageBoxDiv.getSize().x + 160,
			    left: (window.getSize().x / 2) - ((this.imageBoxDiv.getSize().x + 160) / 2)
			});*/
		},
		controlBoxToggle: function() {
				if (this.parent.activeImage().fullImageObj.retrieve("origSize") != null) {
					this.plusSign.setStyles({
						"opacity": 1,
						"cursor": "pointer"
					});
					this.minusSign.setStyles({
						"opacity": 0.3,
						"cursor": "default"
					});
				} else {
					this.plusSign.setStyles({
						"opacity": 0.3,
						"cursor": "default"
					});
					this.minusSign.setStyles({
						"opacity": 1,
						"cursor": "pointer"
					});
				}
				if (this.controlBoxHasSlid) {
					this.controlBox.setStyle("right", 0)
				}
				else {
					var morph = function(){
						this.controlBox.morph({
							right: 0
						})
					}
					morph.delay(500,this);
					this.controlBoxHasSlid = true;
				}
		},
		makeDraggableImage: function(yesorno) {
			if (yesorno == true) {
				this.parent.activeImage().fullImageObj.store("drag",this.parent.activeImage().fullImageObj.makeDraggable({
					onComplete: function(){
						var hOff = this.imageBoxDiv.getSize().x - 2 -(this.parent.activeImage().fullImageObj.width + this.parent.activeImage().fullImageObj.getStyle("left").toInt());
						var vOff = this.imageBoxDiv.getSize().y - 2 -(this.parent.activeImage().fullImageObj.height + this.parent.activeImage().fullImageObj.getStyle("top").toInt());
						if (hOff > 0 || vOff > 0 || this.parent.activeImage().fullImageObj.getStyle("left").toInt() > 0 || this.parent.activeImage().fullImageObj.getStyle("top").toInt() > 0) {
							var morphObj = {};
							if (hOff > 0) {
								morphObj.left = this.parent.activeImage().fullImageObj.getStyle("left").toInt() + hOff;
							}
							else if (this.parent.activeImage().fullImageObj.getStyle("left").toInt() > 0) {
									morphObj.left = 0;
								}
							if (vOff > 0) {
								morphObj.top = this.parent.activeImage().fullImageObj.getStyle("top").toInt() + vOff;
							}
							else if (this.parent.activeImage().fullImageObj.getStyle("top").toInt() > 0) {
									morphObj.top = 0;
								}
							this.parent.activeImage().fullImageObj.store("morphInProgress", true);
							
							this.parent.activeImage().fullImageObj.morph(morphObj);
						}
					}.bind(this),
					onSnap: function(){
						if (this.element.retrieve("morphInProgress") == true) {
							this.element.get("morph").cancel();
						}
					}
				}));
				this.parent.activeImage().fullImageObj.setStyle("cursor", "move");
				this.parent.activeImage().fullImageObj.setStyles({
					"top": 0,
					"left": 0
				});
				// Bug fix for IE not dragging correctly.
				if (Browser.Engine.trident && Browser.Engine.version <= 5) {
					this.parent.activeImage().fullImageObj.ondragstart = function(){
						return false
					}
				}
			} else {
				if (this.parent.activeImage().fullImageObj.retrieve("drag")) {
					this.parent.activeImage().fullImageObj.retrieve("drag").detach();
				}
				this.parent.activeImage().fullImageObj.setStyle("cursor", "default");
			}
		},
		isImageBiggerThanBox: function(image) {
			
			if (
				image.get("width") < (this.imageBoxContainerDiv.getSize().x - 20) &&
				image.get("height") < (this.imageBoxContainerDiv.getSize().y - 20)
			) {
				return false;
			} else {
				return true;
			}
		},
		dispose: function() {
			window.removeEvent("resize",this.resizeAction)
			if (this.parent.images) {
				for (var x = 0; x < this.parent.images.length; x++) {
					if (this.parent.images[x].fullImageObj) {
						this.parent.images[x].fullImageObj.dispose();
						this.parent.images[x].fullImageObj = null;
					}
				}
			}
			
			this.div.dispose();
		},
		resizeBigImage : function() {
			if (this.parent.activeImage().fullImageObj.retrieve("origSize") != null) {
				this.parent.activeImage().fullImageObj.set("width",this.parent.activeImage().fullImageObj.retrieve("origSize").width);
				this.parent.activeImage().fullImageObj.set("height",this.parent.activeImage().fullImageObj.retrieve("origSize").height);
				this.parent.activeImage().fullImageObj.store("origSize",null);
				
			}
			else {
				var horizRatio = (this.imageBoxContainerDiv.getSize().x - 40) / this.parent.activeImage().fullImageObj.get("width");
				var vertRatio = (this.imageBoxContainerDiv.getSize().y - 40) / this.parent.activeImage().fullImageObj.get("height");
				if (vertRatio < horizRatio) {
					finalRatio = vertRatio;
				}
				else {
					finalRatio = horizRatio;
				}
				this.parent.activeImage().fullImageObj.store("origSize", {
					"width": this.parent.activeImage().fullImageObj.get("width"),
					"height": this.parent.activeImage().fullImageObj.get("height")
				})
				this.parent.activeImage().fullImageObj.set("width", Math.floor(this.parent.activeImage().fullImageObj.get("width") * finalRatio))
				this.parent.activeImage().fullImageObj.set("height", Math.floor(this.parent.activeImage().fullImageObj.get("height") * finalRatio))
				//this.makeDraggableImage(false);
				
				
			}
			this.displayImage(true);
		}
		});
		
	window.addEvent("domready", function() {
        var thumbImgs = $$("a[rel^=thumbToFull:]");
        for (var x=0;x<thumbImgs.length;x++) {
	        var imghandler = new SingleImageDisplayer(thumbImgs[x]);
        }
	
	
})



// Neighbourhood selectors

var SearchHandler = new Class({
    initialize: function(target) {
        var lists = target.getFirst("div.scrollbox").getElements("tr.selectorbox");
	    var solo;
	    
	    if (lists.length == 1 && $('nearbylocations') == null) {
	        solo = "solo"
	    } else {
	        solo = "multiple"
	    }
	    
	    
	    
	    for (var x=0;x<lists.length;x++) {
	        if (lists[x].hasClass("nearbylocations")) {
	            new NeighbourhoodPanel({
		            htmltarget: lists[x],
		            mode: "nearby",
		            parent: this
		            })
	        } else {
		        new NeighbourhoodPanel({
		            htmltarget: lists[x],
		            mode: solo,
		            parent: this
		            })
		    }
	    }
	    
	    /*if (target.getFirst("div[class=scrollbox]").getScrollSize().y > 250) {
	        target.getFirst("div[class=scrollbox]").setStyles({
	            height: "250px",
	            overflow: "auto",
	            "max-height": "inherit"
	        });
	        target.getFirst("div[class=scrollbox]").set("morph",{duration:300, transition: Fx.Transitions.Sine.easeOut});
	    }*/
    }
});


function setupNeighbourhoodSelectors(target){
	
	
}

var NeighbourhoodPanel = new Class({
	initialize: function (arguments) {
		this.element = $(arguments.htmltarget);
		this.mode = arguments.mode;
		this.scrollBox = this.element.getParent();
		this.selectPanel = this.element.getNext().getElement(".selectpanel");
		this.nhoodnumber = this.element.getElement(".nhoodnumber");
		this.slidePanel = this.element.getNext().getElement(".inithidepanel");
		this.showHideSelector = this.element.getElement(".showhideselector");
		this.headerCheck = this.element.getElement(".selectheader");
		this.slidePanel.set("morph", {duration: 300, transition: Fx.Transitions.Sine.easeOut});
		this.parent = arguments.parent;
		
		this.panelIsVisible = false;
		if ((arguments.mode == "multiple" || arguments.mode == "nearby") && this.showHideSelector) {
			this.showHideSelector.addEvent("click", this.showHideAction.bind(this));
			
			this.headerCheck.addEvent("click", this.headerCheckAction.bind(this));
		}
		if (this.selectPanel.getElements("td[class=label]").length > 1 || arguments.mode == "nearby") {
		    this.element.getElement(".nhoodnumber").set("html","0");
		    this.initCheckedNumber();
		    this.element.getNext().getElement(".all").addEvent("click", function() {this.selectAll(true) }.bind(this));
		    this.element.getNext().getElement(".none").addEvent("click", function() {this.selectAll(false) }.bind(this));
		    if (this.element.getNext().getElement(".hidewindow")) {
		       this.element.getNext().getElement(".hidewindow").addEvent("click", this.showHideAction.bind(this));
		       }
		}
		this.panelIsVisible = this.slidePanel.getStyle("display") == "block";
	},
	initCheckedNumber: function() {
		this.numberSelected = 0;
		var checks = this.selectPanel.getElements("input[type=checkbox]");
		this.numberTotal = checks.length;
		for (var x=0;x<checks.length;x++) {
			if (checks[x].get("checked") == "checked" || checks[x].get("checked") == true) {
				this.numberSelected++;
			};
			checks[x].addEvent("click", this.checkboxClick.bind(this));
		}
		this.setNumberField();
		if (this.headerCheck) {
			if (this.numberSelected == 0) {
				this.headerCheck.set("checked", false)
			}
			else 
				if ((this.numberSelected > 0) && (this.headerCheck.get("checked") == false)) {
					this.headerCheck.set("checked", true)
				}
		}
	},
	setNumberField: function() {
		this.nhoodnumber.set("html",captable[1081].replace("#x#",this.numberSelected).replace("#y#",this.numberTotal) + " ");
		
		if (this.numberSelected == this.numberTotal) {
		    this.element.getNext().getElement(".all").addClass("depressed");
			this.element.getNext().getElement(".none").removeClass("depressed");
		} else if (this.numberSelected == 0) {
		    this.element.getNext().getElement(".all").removeClass("depressed");
			this.element.getNext().getElement(".none").addClass("depressed");
		} else {
		    this.element.getNext().getElement(".all").removeClass("depressed");
			this.element.getNext().getElement(".none").removeClass("depressed");
		}
	},
	showHideAction: function() {
		if (this.panelIsVisible == false) {
			this.show();
		} else {
			this.hide();
		}
	},
	show: function() {
	    
	    if (this.parent.selectedPanel != null && this.parent.selectedPanel != this) {
	        this.parent.selectedPanel.hide();
	    }
		this.slidePanel.setStyles({
			"display": "block"
			,"height": 0,
			"overflow": "hidden",
			"clear": "left"
		})
		if(this.scrollBox.getStyle("overflow") == "auto") {
		    this.scrollBox.morph({
		        height: this.scrollBox.getStyle("height").toInt() + this.slidePanel.getScrollSize().y
		    });
		}
		this.slidePanel.morph({
			"height" : this.slidePanel.getScrollSize().y
		});
		this.showHideSelector.set("html","(" + captable[1083].toLowerCase() + ")");
		this.panelIsVisible = true;
		this.parent.selectedPanel = this;
		this.headerCheck.getParent("tr.selectorbox").addClass("openbox");
	},
	hide: function() {
	    
	    if (this.parent.selectedPanel == this) {
	        this.parent.selectedPanel = null;
	    }
		this.slidePanel.morph({
			"height": 0
		});
		if(this.scrollBox.getStyle("overflow") == "auto") {
		    this.scrollBox.morph({
		        height: this.scrollBox.getStyle("height").toInt() - this.slidePanel.getScrollSize().y 
		    });
		}
		var hidePanel = function(){
			this.slidePanel.setStyles({
				"display": "none"
			});
		};
		hidePanel.delay(300,this);
		this.showHideSelector.set("html","(" + captable[1082] + ")");
		this.headerCheck.getParent("tr.selectorbox").removeClass("openbox");
			this.panelIsVisible = false;
	},
	checkboxClick: function(e) {
		if (e.target.get("checked") == false) {
			this.numberSelected = this.numberSelected - 1;
		} else {
			this.numberSelected = this.numberSelected + 1;
		}
		this.setNumberField();
		if (this.headerCheck) {
			if (this.numberSelected == 0) {
				this.headerCheck.set("checked", false)
			}
			else 
				if ((this.numberSelected > 0) && (this.headerCheck.get("checked") == false)) {
					this.headerCheck.set("checked", true)
				}
		}
	},
	headerCheckAction: function() {
	   //this.selectAll(this.headerCheck.get("checked"));
		if (this.panelIsVisible == false && (this.selectPanel.getElements("td").length > 1 || this.mode == "nearby")) {
		    this.show();
		} else {
		    this.hide();
		}
	},
	selectAll: function(y) {
		if (y == true) {
			this.selectPanel.getElements("input").set("checked", true);
			this.numberSelected = this.numberTotal;
			this.setNumberField();
			if (this.headerCheck) {
				this.headerCheck.set("checked", true);
			}
			
		} else {
			this.selectPanel.getElements("input").set("checked", false);
			this.numberSelected = 0;
			this.setNumberField();
			if (this.headerCheck) {
				this.headerCheck.set("checked", false)
			}
			
		}
	}
})




var AjaxProRequest = new Class({
    Extends: Request,
    initialize: function(arguments) {
        this.arguments = arguments;
        this.nSpace = arguments.nSpace;
        this.parent({
            method: "post",
            url: "/ajaxpro/" + this.nSpace + ",Erm.Web.ashx",
            onSuccess: function() {
                // MooTools appends "value:{}" to returned strings. This is a pain, so we remove it.
                returnobj = JSON.decode(JSON.decode(this.response.text).value);
                if (this.arguments.onSuccess) {
                    this.arguments.onSuccess.run([{json: returnobj}, this.arguments.onSuccessParams]);
                }
            }.bind(this),
            onFailure: arguments.onFailure,
            data: JSON.encode(arguments.arguments),
            headers: {    
                "Content-Type": "text/plain; charset=utf-8",   
                "X-AjaxPro-Method": arguments.methodName,
                "Accept" : "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"
            },
            urlEncoded: false
        });
    }
});

function isemail(s) {
	        return ((trim(s).length > 0) && (s.indexOf('@') > 0) && (s.substring(s.length-1) != '@') &&  
            (s.indexOf('@') == s.lastIndexOf('@')) && (s.indexOf('.') > 0) && (s.substring(s.length-1) != '.') && 
            (s.indexOf('.@') == -1) && (s.indexOf('@.') == -1) && (s.indexOf('..') == -1) && (s.indexOf(' ') == -1) && 
            (s.indexOf('\t') == -1) && (s.indexOf('\n') == -1) && (s.indexOf('\r') == -1));
            }
            //function to remove the whitespaces from the start and end of a string
            function trim(s) {
	        regl = /^[ \t\n\r]*/
	        regr = /[ \t\n\r]*$/
	        return s.replace(regl,'').replace(regr,'');
            }
            // function to validate fields
            function dovalid1(){
            var errmsg='';
            var focuson;
            if (trim(document.frmlogin.txtemail.value) == '' || trim(document.frmlogin.txtemail.value) == captable[435]){
            errmsg = errmsg + captable[436] + '<br/>';
            focuson = typeof(focuson) == 'object' ? focuson : document.frmlogin.txtemail;
            }else if (!isemail(document.frmlogin.txtemail.value)){
            errmsg = errmsg + captable[437] + '<br/>';
            focuson = typeof(focuson) == 'object' ? focuson : document.frmlogin.txtemail;
            }
            if (trim(document.frmlogin.txtpassword.value) == '' || trim(document.frmlogin.txtpassword.value) == captable[27]){
            errmsg = errmsg + '<br/>'+captable[439];
            focuson = typeof(focuson) == 'object' ? focuson : document.frmlogin.txtpassword;
            } 
            if(errmsg != ''){ 
            ErmJS.Controls.alert(errmsg);
            focuson.focus();
            return false;
            }
            else
            {
            return true;
            }
            }
            // function to perform login check
            function logincheck(){
            if(dovalid1()){
            return true;
            }
            else
            return false;
            }