﻿var	DisableRollOver=false;
var prevITEMID=0;
var g_TypeOfControl='';
var glb_balloonLeft=0;

var Balloon = Class.create();
Balloon.prototype = {

	STATES : { DEFLATED : 0, INFLATING : 1, INFLATED : 2 },
	
	VERTICAL_POSITIONS : { UPPER : 0, LOWER : 1 },
	HORIZONTAL_POSITIONS : { LEFT : 0, RIGHT : 2 },
 
	state : 0,
	anchor : null,
	elements : { balloon : 'balloon', balloonArrow : 'balloonArrow', balloonArrowUL : 'balloonArrowUL', balloonArrowUR : 'balloonArrowUR', balloonArrowLL : 'balloonArrowLL', balloonArrowLR : 'balloonArrowLR' },

	initialize : function(url, anchor) {
		this.state = this.STATES.DEFLATED;
		this.url = url;
		this.anchor = anchor;
	},
	
	inflate : function() {
		this.state = this.STATES.INFLATING;
		params = this.url;
		new Ajax.Request('/swapbar/specs.aspx', {parameters:params, onComplete:this.process.bind(this)});	
	},
	
	process : function(response) {
		this.state = this.STATES.INFLATED;
		this.html = response.responseText;
		balloonPilot.wake(this);
	},
	
	position : function() {
		// positions
		var balloonDimensions = Element.getDimensions(this.elements.balloon);
		var offsets = Position.cumulativeOffset(this.anchor);
		var deltas  = Position.Window.getDeltas();
		var windowDimensions = Position.Window.size();
		var anchorDimensions = Element.getDimensions(this.anchor);
		var quadrant = this.VERTICAL_POSITIONS.UPPER + this.HORIZONTAL_POSITIONS.LEFT;

		//logger.debug("balloon: " + balloonDimensions.width +":"+balloonDimensions.height + ", offsets: " + offsets + ", deltas: " + deltas.x + ":" + deltas.y + ", window: " + windowDimensions.width+":"+windowDimensions.height);
		
		// default baseline position
		var baseline = { x : offsets[0], y : offsets[1] - balloonDimensions.height/4 };
		var moveLeft = 0
		var moveTop = 0
		var moveTopLowerQuad = 0

	    switch(parseInt(g_TypeOfControl)) {
			case 0:  //ImageRollover
				moveLeft = 35; 
				moveTop = 30;
				break;
				//alert("ImageRollover");
			case 1: //TextRolloverShowImg 
			case 2: //TextRolloverNoImg
				// code for case 1 AND case 2, b/c there's no break in case 1
				moveLeft = 0;
				moveTop = 0;
				moveTopLowerQuad = - 60  //to fix problems at bottom of screen
				break;
	    }
		

		// setTop		
		var top = baseline.y;
		if (baseline.y + balloonDimensions.height > windowDimensions.height + deltas.y) {
			top = windowDimensions.height + deltas.y - balloonDimensions.height;
			quadrant += this.VERTICAL_POSITIONS.LOWER;
		}  else if (baseline.y < deltas.y) {
			top = deltas.y;
		}
				
		$(this.elements.balloon).style.top = "" + top + "px";
		
		// setLeft
		var left = baseline.x + anchorDimensions.width + 35;
		if (baseline.x + anchorDimensions.width > windowDimensions.width/2) {
			left = offsets[0] - 262 - 35;
			quadrant += this.HORIZONTAL_POSITIONS.RIGHT;
		}
		$(this.elements.balloon).style.left = left+"px";
			
		glb_balloonLeft = left;		
		
		// setArrow
		var arrowTop = 0;
		switch(quadrant) {
			case 0:
				$(this.elements.balloonArrow).style.left = left - 43 + "px";
				arrowTop = offsets[1] + moveTop; //change this to change the location of the arrow tip
				Element.show(this.elements.balloonArrowUL);
				break;
			case 1:
				$(this.elements.balloonArrow).style.left = left - 43 + "px";
				arrowTop  = offsets[1] - moveTop + moveTopLowerQuad;
				Element.show(this.elements.balloonArrowLL);
				break;
			case 2:
				$(this.elements.balloonArrow).style.left = left + 260 + "px";
				arrowTop = offsets[1] + moveTop;
				Element.show(this.elements.balloonArrowUR);
				break;
			case 3:
				$(this.elements.balloonArrow).style.left = left + 260 + "px";
				arrowTop = offsets[1] - moveTop + moveTopLowerQuad;
				Element.show(this.elements.balloonArrowLR);
				break;
		}

		if (arrowTop + 77 > windowDimensions.height + deltas.y) {
			arrowTop = windowDimensions.height + deltas.y - 77;
		} else if (arrowTop < deltas.y) {
			arrowTop = deltas.y;
		}

		$(this.elements.balloonArrow).style.top = arrowTop + "px";
		
	},
	
	paint : function() {
		$('popupdata').update(this.html);
		Effect.Appear(this.elements.balloon, {duration:0.5});	
		Effect.Appear(this.elements.balloonArrow, {duration:0.5});	
		this.position();
	},
	
	hide : function() {
		Element.hide(this.elements.balloon);
		Element.hide(this.elements.balloonArrow);	
		Element.hide(this.elements.balloonArrowUR);
		Element.hide(this.elements.balloonArrowUL);
		Element.hide(this.elements.balloonArrowLR);
		Element.hide(this.elements.balloonArrowLL);
	}
};

var balloonPilot = {

	cache : new Array(),
	
	requested : null,
	pending : null,
	hiding : null,
	findOrAdd : function(url, node) {
		for (i=0;i<this.cache.length;i++) {
			if (url == this.cache[i].url) {
				this.cache[i].anchor = node;
				return this.cache[i];
			}
		}
		var balloon = new Balloon(url);
		balloon.anchor = node;
		this.cache.push(balloon);
		return balloon;
	},

	show : function(node, url) {
		
		this.requested = this.findOrAdd(url, node);
		
		switch (this.requested.state) {
			case this.requested.STATES.DEFLATED: 
				this.pending = setTimeout(this.requested.inflate.bind(this.requested), 800);
				break;
			case this.requested.STATES.INFLATING:
				break;
			case this.requested.STATES.INFLATED:
				this.pending = setTimeout(this.requested.paint.bind(this.requested), 800);
				break;				
		}
	},
	
	wake : function(balloon) {
		if (balloon == this.requested) {
			balloon.paint(balloon.anchor);
		}
	},

	hide : function() {
		prevITEMID=0;
		if (this.requested != null) {
			this.requested.hide();
			this.requested = null;	
		}
		if (this.pending != null) {
			clearTimeout(this.pending);
			this.pending = null;
		}
	},
	delFromCache :function(url)	{
		//alert(url);
		for (i=0;i<this.cache.length;i++) {
			if (this.cache[i].url.indexOf(url)>0) {
				//alert('hi');
				this.cache.splice(i,1)
				return;
			}
		}
	}

};
var movieBalloon = {

	show : function(event, itemId, az, typeOfControl) {
		//disable rollover
		//
		if(DisableRollOver==true) {
			return;
		}
		//
		if (balloonPilot.hiding!=null) {  
			window.clearTimeout(balloonPilot.hiding);
			balloonPilot.hiding=null;
		}
		if(prevITEMID==itemId) {
			return true;	
		}
		this.hide('');
		var node = Event.element(event);
		prevITEMID=itemId;
		
		g_TypeOfControl=typeOfControl; 
		var url  = "itemId=" + itemId + "&az=" + az;	
		balloonPilot.show(node, url);
	},
	
	hide : function(strOption) {
		//disable rollover
		//
		if(DisableRollOver==true) {
			return;
		}
		//
		if (balloonPilot.hiding!=null) {  
			window.clearTimeout(balloonPilot.hiding);
			balloonPilot.hiding=null;
		}
		if(strOption=='max') {
			//put more delay on link for which popup to be shown
			balloonPilot.hiding=window.setTimeout(function(){balloonPilot.hide();}, 1000);
		} else if(strOption=='med') {
			//put delay but execute faster
			balloonPilot.hiding=window.setTimeout(function(){balloonPilot.hide();}, 400);
		} else {
			balloonPilot.hide();
		}
	},
	
	dontHide : function() {
		//disable rollover
		if(DisableRollOver==true) {
			return;
		}
		if (balloonPilot.hiding!=null) {
			window.clearTimeout(balloonPilot.hiding);
			balloonPilot.hiding=null;
		}
	},
	
	delFromCache : function(itemId) {
		balloonPilot.delFromCache(itemId);
	}
};

var userBalloon = {

	show : function(event, userId) {
		this.hide();
		var node = Event.element(event);
		var url  = "viewUserBalloon=&userId="+userId;	
		balloonPilot.show(node, url);	
	},
	
	hide : function() {
		balloonPilot.hide();
	}
};


var actorBalloon = {

	show : function(event, actorId) {
		this.hide();
		var node = Event.element(event);
		var url  = "viewActorBalloon=&actorId="+actorId;
		balloonPilot.show(node, url);
	},
	
	hide : function() {
		balloonPilot.hide();
	}
};


/*------------PROTOTYPE EXTENSIONS---------------------*/
Position.Window = {
    getDeltas: function() {
        var deltaX =  window.pageXOffset || document.documentElement.scrollLeft || document.body.scrollLeft || 0;
        var deltaY =  window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop || 0;
        return { x : deltaX, y : deltaY };
    },
    size: function() {
        var winWidth, winHeight, d=document;
        if (typeof window.innerWidth!='undefined') {
            winWidth = window.innerWidth;
            winHeight = window.innerHeight;
        } else {
            if (d.documentElement && typeof d.documentElement.clientWidth!='undefined' && d.documentElement.clientWidth!=0) {
                winWidth = d.documentElement.clientWidth
                winHeight = d.documentElement.clientHeight
            } else {
                if (d.body && typeof d.body.clientWidth!='undefined') {
                    winWidth = d.body.clientWidth
                    winHeight = d.body.clientHeight
                }
            }
        }
        return {width : winWidth, height : winHeight};
    }
};

var DepartmentView = Class.create();
DepartmentView.prototype = {
    isLoaded : false,
    isVisible : false,
    scroll : 10,
    timerID : 0,
    top : 0,

    initialize : function() {
        //Event.observe($('buttonCat').childNodes[1], 'click', this.toggle.bind(this));
        Event.observe($('catOpen'), 'click', this.toggle.bind(this));
    },
    getCategories : function() {
        var url = '/ajax/searcher/departments.aspx';
        
        new Ajax.Updater('deptDiv', url, {method:'get',evalScripts: true, onComplete: this.show.bind(this)});	
        
        // scroll down
        Event.observe($('catScrollDown'), "mouseover", this.scrollDown.bind(this));
        Event.observe($('catScrollDown'), "mouseout", this.scrollStop.bind(this));
        
        // scroll up
        Event.observe($('catScrollUp'), "mouseover", this.scrollUp.bind(this));
        Event.observe($('catScrollUp'), "mouseout", this.scrollStop.bind(this));
        
        //$('catScrollUp').style.display = 'none';
    },
    hide : function() {
        $('catButton').style.display = 'none';   
        
        this.isVisible = false; 
    },
    scrollUp : function() {
        if (this.timerID > 0)
            clearTimeout(this.timerID);
            
        this.top -= this.scroll;             
        this.top = (this.top < 0 ? 0 : this.top);
          
        $('deptDiv').scrollTop = this.top;
        
        this.timerID = setTimeout(this.scrollUp.bind(this), 250);
    },
    scrollDown : function() {
        $('catScrollUp').style.display = 'block';
        
        if (this.timerID > 0)
            clearTimeout(this.timerID);
            
        this.top += this.scroll;        
        $('deptDiv').scrollTop = this.top;
        
        this.timerID = setTimeout(this.scrollDown.bind(this), 250);
    },
    scrollStop : function() {
        clearTimeout(this.timerID);
    },
    show : function() {
        if (!this.isLoaded)
        {
            this.getCategories();       
                                                                   
            this.isLoaded = true;                 
        }
        
        $('catButton').style.display = 'block';    
                
        this.isVisible = true;
    },
    toggle : function() {
        this.isVisible ? this.hide() : this.show();
        
        $('catOpen').className = (this.isVisible ? 'catClose' : 'catOpen');
    }
};
var StatusMenu = Class.create();
StatusMenu.prototype = {
    initialized : false,
    statusDiv : null,
    statusMenu : null,
    
    initialize : function() {
    
        if (!this.initialized)
        {
            this.statusMenu = $('statusLink');
            
            Event.observe(this.statusMenu, 'mouseover', this.show.bind(this));
            Event.observe(this.statusMenu, 'mouseout', this.hide.bind(this));
            
            // create the div
            this.statusDiv = document.createElement("div");            
            this.statusDiv.appendChild(document.createElement("ul"));
                        
            this.statusDiv.firstChild.appendChild(this.createLink('Available', 'JavaScript:changeOnlineStatus(1);'));
            this.statusDiv.firstChild.appendChild(this.createLink('Offline', 'JavaScript:changeOnlineStatus(0);'));
            this.statusDiv.firstChild.appendChild(this.createLink('Log Off', '/logoff.aspx'));

            this.statusDiv.className = 'statusMenu';
            
            this.statusMenu.appendChild(this.statusDiv);
            
            this.statusMenu.lastChild.style.display = 'none';
        }
            
        this.initialized = true;
    },
    createLink : function(caption, link) {
    
        var hLink = document.createElement('a');
        var txt = document.createTextNode(caption);

        hLink.appendChild(txt);
        hLink.setAttribute('href',link);
        
        var item = document.createElement('li');
        item.appendChild(hLink);
               
        return item;
    },
    hide : function() {
        this.statusMenu.lastChild.style.display = 'none';
        
        $('statusImg').src='/images/icons/arrow_grayright.gif';
    },
    show : function() {    
        this.statusMenu.lastChild.style.display = 'block';
        
        $('statusImg').src='/images/icons/arrow_graydown.gif';
    }
};
var CatChooser = Class.create();
CatChooser.prototype = {
    category : -1,
    catMenu : null,
    initialized : false,
    loaded : false,
    timerID : 0,
    
    initialize : function() {
        this.catMenu = $('catChooser');
        
        this.getCategories();
        
        Event.observe($('chooseMenu'), 'mouseover', this.show.bind(this));
        Event.observe($('chooseMenu'), 'mouseout', this.doHide.bind(this));
        Event.observe($('catHover'), 'mouseover', this.show.bind(this));
        Event.observe($('catHover'), 'mouseout', this.doHide.bind(this));
    },
    doHide : function() {    
        this.timerID = setTimeout(this.hide.bind(this), 300);
    },
    getCategories : function() {
        var url = '/ajax/searcher/catChooser.aspx';
        new Ajax.Request(url, {method:'get', onComplete : this.loadCategories.bind(this)});	
    },
    hide : function() {
        this.catMenu.style.display = 'none';
    },
    loadCategories : function(response) {
        $('catHover').innerHTML = response.responseText;
    },
    select : function(id, img) {
        $('searchIcon').src = '/images/icons/searcher/' + img;
                
        this.category = id;
        this.hide();
    },
    show : function() {
        if (this.timerID > 0)
            clearTimeout(this.timerID);
        this.catMenu.style.display = 'block';
    },
    submit : function() {
    
        var params = 'parentCatID=' + this.category;
        switch(this.category)
        {
            case '-5':
                params = 'section=users';
                break;
        }
        document.location.href = 'results.aspx?' + params + '&searchTxt=' + $('searcherBox').value;
    }
};
var PowerSearcher = Class.create();
PowerSearcher.prototype = {
    active : false,
    advancedBtn : null,
    changed : false,
    hasFocus : false,
    initialized : false,
    element : null,
    observer : null,
    searchBox : null,
    url : '/ajax/searcher/keyword.aspx',
    
    initialize : function() {
        this.element = $('chooseCat');
        this.searchBox = $('searcherBox');
        this.advancedBtn = $('advancedSearch');
                
        Event.observe(this.searchBox, "keypress", this.onKeyPress.bindAsEventListener(this));
        Event.observe(this.searchBox, "blur", this.onBlur.bindAsEventListener(this));
        
        Event.observe($('advSearchButton'), "click", this.collapse.bind(this));
        
        Element.addClassName(this.advancedBtn,'closed');
        
        this.initialized = true;
    },
    getUpdatedChoices: function() {
        if (this.searchBox.value.length > 2) {
            var params = 'prefixText=' + this.searchBox.value + '&category=' + ChooserMenu.category;
        
            new Ajax.Updater('powerSearchResults', this.url, {parameters:params, onComplete: this.show.bind(this)});
        }
    },
    hide : function() {
        this.searchBox.value = 'Enter Keyword or Title';
        this.element.style.display = 'none';
    },
    show : function() {
        this.element.style.display = 'block';
        this.active = true;
    },
    onBlur : function(event) {
        // needed to make click events working
        setTimeout(this.hide.bind(this), 250);
        this.hasFocus = false;
        this.active = false;     
    },
    onKeyPress : function(event) {
        if(this.active)
          switch(event.keyCode) {
           case Event.KEY_TAB:
           case Event.KEY_RETURN:
             //this.selectEntry();
             Event.stop(event);
           case Event.KEY_ESC:
             this.hide();
             this.active = false;
             Event.stop(event);
             return;
           case Event.KEY_LEFT:
           case Event.KEY_RIGHT:
             return;
           case Event.KEY_UP:
             //this.markPrevious();
             //this.render();
             if(navigator.appVersion.indexOf('AppleWebKit')>0) Event.stop(event);
             return;
           case Event.KEY_DOWN:
             //this.markNext();
             //this.render();
             if(navigator.appVersion.indexOf('AppleWebKit')>0) Event.stop(event);
             return;
          }
         else 
           if(event.keyCode==Event.KEY_TAB || event.keyCode==Event.KEY_RETURN || 
             (navigator.appVersion.indexOf('AppleWebKit') > 0 && event.keyCode == 0)) return;

        this.changed = true;
        this.hasFocus = true;

        if(this.observer) clearTimeout(this.observer);
        this.observer = setTimeout(this.onObserverEvent.bind(this), 1000);
    },
    onObserverEvent: function() {
        this.changed = false;   
        if(this.searchBox.value.length>=2) {
          this.getUpdatedChoices();
        } else {
          this.active = false;
        }
    },
    collapse : function(e) {
		var el = this.advancedBtn;
		if ( Element.hasClassName(el,'closed') ) {
			new Effect.Parallel(
				[
					new Effect.SlideDown(el,{sync:true}),
					new Effect.Appear(el,{sync:true})
				],
				{
					duration:1.0,
					fps:40
				}
			);
			Element.removeClassName(el,'closed');
		} else {
			new Effect.Parallel(
				[
					new Effect.SlideUp(el,{sync:true}),
					new Effect.Fade(el,{sync:true})
				],
				{
					duration:1.0,
					fps:40
				}
			);
			Element.addClassName(el,'closed')
		}
	},
	resetForm : function(baseId) {
	    
	    $('imgLoading').style.display = 'block';
        
        baseId = baseId.substring(0, baseId.lastIndexOf('_') + 1);
        
        $(baseId + 'txtKword').value = 'Enter keyword(s)';
        $(baseId + 'txtUname').value = 'Enter user name';
        $(baseId + 'dlSort').selectedIndex = 0;
        $(baseId + 'txtZip').value = 'Enter Zip';
        $(baseId + 'dlRadius').selectedIndex = 0;
        $(baseId + 'filterSV').checked = false;
        $(baseId + 'filterFP').checked = false;
        $(baseId + 'filterHave').checked = false;
        $(baseId + 'filterWant').checked = false;
        $(baseId + 'condN').checked = false;
        $(baseId + 'condE').checked = false;
        $(baseId + 'condVG').checked = false;
        $(baseId + 'condG').checked = false;
        $(baseId + 'condF').checked = false;
        $(baseId + 'condP').checked = false;
        
        $('imgLoading').style.display = 'none';
	}
};
var WishlistBox = Class.create();
WishlistBox.prototype = {
    _element : null,
    _scatId : null,
    
    initialize : function(element, itemId, scatId) {
        this._element = $(element);
        this._itemId = itemId;
        this._scatId = scatId;
        
        var menuDiv = document.createElement('div');
        menuDiv.className = 'roundedBox selectBox';
        menuDiv.innerHTML = '<div class=hd><div class=c></div></div><div class=bd><div style="margin:0"></div></div><div class=ft><div class=c></div></div>';
        
        var contentDiv = menuDiv.childNodes[1].firstChild;
        
        var txt = document.createElement('h3');
        txt.innerHTML = 'Enter Items you want for this one';
        
        contentDiv.appendChild(txt);
        
        var wishlist = document.createElement('textarea');
        wishlist.style.height = '92px';
        wishlist.style.width = '286px';
         
        contentDiv.appendChild(wishlist);
        
        contentDiv.appendChild(document.createElement('br'));
        contentDiv.appendChild(document.createElement('br'));
         
         var saveBtn = document.createElement('input');
         saveBtn.type = 'button';
         saveBtn.value = 'Save';
         
         contentDiv.appendChild(saveBtn);
         
         Event.observe(contentDiv.lastChild, 'click', this.save.bind(this));
         
        var wrapper = document.createElement('div');
        wrapper.style.position = 'absolute';
        wrapper.appendChild(menuDiv);
         
        this._element.appendChild(wrapper);
        this._wishlist =  this._element.lastChild.firstChild.childNodes[1].firstChild.childNodes[1];
        
        Effect.Shake(this._element);
    },
    save : function() {
        var params = "itemId=" + this._itemId + "&scatId=" + this._scatId + '&wishlist=' + encodeURIComponent(this._wishlist.value);
        
        new Ajax.Request('/ajax/item/categories.aspx', { parameters: params, method:'get', onComplete: this.destroy.bind(this) });
    },
    
    destroy : function() {
        this._element.removeChild(this._element.lastChild);
    }
};
var CatSelector = Class.create();
CatSelector.prototype = {
    _categories : null,
    _element : null,
    _itemId : null,
    _itemType : null,
    _saveButton : null,
    _subcategories : null,
    _wishlist : null,
    
    initialize : function(element, itemId, itemType) { 
        this._element = $(element);
        this._itemId = itemId;
        this._itemType = itemType;
        
        // attach to the element
        new Ajax.Request('/ajax/item/selector.aspx', { method:'get', onComplete: this.updateDepartments.bind(this) });
    },
    updateDepartments : function(t) {
        var menuDiv = document.createElement('div');
        menuDiv.className = 'roundedBox selectBox';
        menuDiv.innerHTML = '<div class=hd><div class=c></div></div><div class=bd><div style="margin:0"></div></div><div class=ft><div class=c></div></div>';
        
        var data = eval('(' + t.responseText + ')');
        
        // build the drop down
        var contentDiv = menuDiv.childNodes[1].firstChild;
        
        var categories = document.createElement('select');
        for (var i=0; i < data.options.length; i++)
            categories.options[categories.options.length] = new Option(data.options[i].name, data.options[i].value);
        
        contentDiv.appendChild(categories);
        
        Event.observe(contentDiv.lastChild, 'change', this.updateCategories.bind(this));
        
        contentDiv.appendChild(document.createElement('br'));
        contentDiv.appendChild(document.createElement('br'));
        
        var subcategories = document.createElement('select');
        subcategories.options[0] = new Option("Select Sub Category", "-1");
        contentDiv.appendChild(subcategories);
        
        Event.observe(contentDiv.lastChild, 'change', this.catSelected.bind(this));
        
        contentDiv.appendChild(document.createElement('br'));
        contentDiv.appendChild(document.createElement('br'));
        
        if (this._itemType == 1) {
            var txt = document.createElement('h3');
            txt.innerHTML = 'Enter Items you want for this one';
            
            contentDiv.appendChild(txt);
            
            var wishlist = document.createElement('textarea');
            wishlist.style.height = '92px';
            wishlist.style.width = '286px';
             
             contentDiv.appendChild(wishlist);
             
            contentDiv.appendChild(document.createElement('br'));
            contentDiv.appendChild(document.createElement('br'));
        }
         
         var saveBtn = document.createElement('input');
         saveBtn.type = 'button';
         saveBtn.value = 'Select a Category';
         
         contentDiv.appendChild(saveBtn);
         
         Event.observe(contentDiv.lastChild, 'click', this.save.bind(this));
         
        this._element.appendChild(menuDiv);

        this._wishlist = this._element.lastChild.childNodes[1].firstChild.childNodes[7];
        this._subcategories = this._element.lastChild.childNodes[1].firstChild.childNodes[3];
        this._saveButton = this._element.lastChild.childNodes[1].firstChild.lastChild;
        this._saveButton.disabled = true;
        
        Effect.Shake(this._element);
    },
    updateCategories : function() {
        var catId = this._element.lastChild.childNodes[1].firstChild.firstChild.value;
        if (catId != -1) {
            // clear the sub cat drop down
            for (var i = (this._subcategories.options.length - 1); i >= 0; i--)
                this._subcategories.options[i] = null;
                
            this._subcategories[0] = new Option('Select Sub Category', '-1');
            this._saveButton.disabled = true;
            
            var params = "catId=" + catId;
    
            new Ajax.Request('/ajax/item/categories.aspx', { parameters: params, method:'get', onComplete: this.populateDropDown.bind(this) });
        }
    },    
    populateDropDown : function(t) {
        var options = eval(t.responseText);
        
        for (var i = 0; i < options.length; i++) {
            var elOptNew = document.createElement('option');
            elOptNew.text = options[i].text;
            elOptNew.value = options[i].value;
            
            try {
                this._subcategories.add(elOptNew, null); // standards compliant; doesn't work in IE
              }
              catch(ex) {
                this._subcategories.add(elOptNew); // IE only
              }
        }
        
        this._saveButton.value = 'Select Sub Category';
    },
    catSelected : function() {
        var scatId = this._subcategories.value;
        
        if (scatId != -1) {
            this._saveButton.disabled = false;
            this._saveButton.value = 'Save';
        }
    },
    save : function() {
    
        var params = "itemId=" + this._itemId + "&scatId=" + this._subcategories.value + '&wishlist=' + encodeURIComponent(this._wishlist.value);
        
        new Ajax.Request('/ajax/item/categories.aspx', { parameters: params, method:'get', onComplete: this.destroy.bind(this) });
    },
    destroy : function() {
        this._element.removeChild(this._element.lastChild);
    }
};
var QuickList = Class.create();
QuickList.prototype = {
    _itemId : null,
    _sellIt : null,
    
    initialize: function(itemID, listType, sellIt) {
        this._itemId = itemID;
        this._sellIt = sellIt;
        this.addItemToSwapBar(itemID, listType);
    },
    
    addItemToSwapBar : function(itemID, listType) {
        var params = "id=" + itemID + "&act=a&listType=" + listType;
        new Ajax.Request('/ajax/quicklist/inventory.aspx', { parameters: params, method:'get', onComplete: this.itemAdded.bind(this) });
    },
    
    itemAdded : function(response) {
        // JSON returned
        var itemInfo = eval('(' + response.responseText + ')');

        if (this._sellIt !== undefined)
            location.href = '/account-item-details.aspx?itemId=' + itemInfo.itemId + '#sellit';

        // update the search results
        var resId = '';
        
        if (this._itemId.toString().indexOf('asin') > -1) {
            resId = 'action_' + this._itemId;
            
            var savedDiv = document.createElement('div');
            savedDiv.innerHTML = '<div class=info><img src="/images/icons/greendot.gif" width=20 height=20 align=absmiddle> Saved</div>';
            $(resId).innerHTML = savedDiv.innerHTML;
        }
        else {
            resId = (itemInfo.itemType == 1 ? 'tohave_' : 'towant_') + this._itemId;
            
            var savedSpan = document.createElement('span');
            savedSpan.id = resId;
            savedSpan.innerHTML = '<font color=green>Added to your ' + (itemInfo.itemType == 1 ? 'Have It' : 'Want It') + ' List</font>';
            $(resId).innerHTML = savedSpan.innerHTML;
        }
        
        if (itemInfo.asin !== undefined)
            new CatSelector(resId, itemInfo.itemId, itemInfo.itemType);
        else if (itemInfo.itemType == 1)
          new WishlistBox(resId, itemInfo.itemId, itemInfo.catId);
        else if (itemInfo.itemType == 2)
          new WantItMatcher(resId, itemInfo.itemId, itemInfo.matches);
    }
}
var WantItMatcher = Class.create();
WantItMatcher.prototype = {
    _matches : null,
    
    initialize : function(element, itemId, matches) {
        this._element = $(element);
        
        if (matches != undefined) {
            this._matches = {};
            this._matches.matches = matches;
            this.showResults();
        }
        else {
            var params = "itemId=" + itemId;
            new Ajax.Request('/ajax/quicklist/matches.aspx', { parameters: params, method: 'get', onComplete: this.showResults.bind(this) });
        }
    },
    
    showResults : function(resp) {
        if (resp != undefined)
            this._matches = eval('(' + resp.responseText + ')');
    
        if (this._matches.matches.length > 0) {
            var menuDiv = document.createElement('div');
            menuDiv.className = 'roundedBox selectBox';
            menuDiv.innerHTML = '<div class=hd><div class=c></div></div><div class=bd><div style="margin:0"></div></div><div class=ft><div class=c></div></div>';
            
            var contentDiv = menuDiv.childNodes[1].firstChild;
            var tmp = document.createElement('br');
            contentDiv.appendChild(tmp);
            
            tmp = document.createElement('h2');
            tmp.innerHTML = 'Someone Has This Item!';
            contentDiv.appendChild(tmp);
            
            tmp = document.createElement('p');
            tmp.innerHTML = 'The following users have already posted the item that you want. <BR><br>Click the "Create an Offer" link to make a swap';
            contentDiv.appendChild(tmp);
            
            var itemWrapper = document.createElement('div');
            itemWrapper.className = 'itemsContainer';
            itemWrapper.style.overflow = 'auto';
            itemWrapper.style.height = '200px';
            itemWrapper.innerHTML = this._matches.matches;
            
            contentDiv.appendChild(itemWrapper);
            
            tmp = document.createElement('span');
            tmp.innerHTML = '<table><tr><td><img src="images/icons/arrow_grayright.gif" valign=middle></td><td><a href="javascript:void(0);"><b>I do not want to create an offer right now</b></a></td></table>';
            contentDiv.appendChild(tmp);
            
            Event.observe(contentDiv.lastChild, 'click', this.destroy.bind(this));
            
            var wrapper = document.createElement('div');
            wrapper.style.position = 'absolute';
            wrapper.appendChild(menuDiv);
            
            this._element.appendChild(wrapper);
            
            Effect.Shake(wrapper);
        }
    },
    
    destroy : function() {
        this._element.removeChild(this._element.lastChild);
    }
    
};
var Tooltip = Class.create();
Tooltip.prototype = {
    _element : null,
    _toolTip : null,
    
    initialize : function(element, content, arrow) {
        this._element = (typeof(element) === 'object' ? element : $(element));
        
        var tmp = document.createElement('div');
        tmp.className = 'roundedBox tooltip';
        tmp.innerHTML = '<div class="hd"><div class="c"></div></div><div class="bd"></div><div class="ft"><div class="c"></div></div><div></div>';
        
        tmp.childNodes[1].innerHTML = content;
        tmp.lastChild.className = arrow;
        this._element.appendChild(tmp);
    },
    hide : function() {
        Element.hide(this._element);
    },
    show : function() {
        Element.show(this._element);
    }
}

Object.extend(Event, {
        wheel:function (event){
                var delta = 0;
                if (!event) event = window.event;
                if (event.wheelDelta) {
                        delta = event.wheelDelta/120;
                        if (window.opera) delta = -delta;
                } else if (event.detail) { delta = -event.detail/3;     }
                return Math.round(delta); //Safari Round
        }
});

var Pager = Class.create();
Pager.prototype = {
    _currPage : 0,
    _element : null,
    _isUpdating : false,
    _loader : null,
    _preloadDistance : 450,
    _totalPages : 1,
    _url : null, 
    _viewId : 1,
    
    initialize : function(element, url, totalPages, viewId, preloadDistance) {
        this._element = $(element);
        
        //var tmp = document.createElement('div');
        //tmp.innerHTML = '<div id="pgrLoadingData" style="position:fixed;top:40%;left:30%;z-index:1000001;width:100%;display:none;background-color: #FFFFFF"><h1><img src="/images/spinner.gif"> Loading More Results...</h1></div>';
        //document.body.appendChild(tmp);
        
        this._loader = $('pgrLoadingData');
        //attach the handlers
        Event.observe(document, "mousewheel", this.checkGetNextPage.bind(this), false);
        Event.observe(document, "DOMMouseScroll", this.checkGetNextPage.bind(this), false);
        Event.observe(window, "scroll", this.checkGetNextPage.bind(this), false);
        
        if (preloadDistance) this._preloadDistance = preloadDistance;
        if (viewId) this._viewId = viewId;
        
        this._totalPages = totalPages;
        this._url = url;
        
        this.getNextPage(1, this._viewId);
    },
    checkGetNextPage : function(e) {
        if (!this._isUpdating && this.getPageHeight() - this.getScrollHeight() < this._preloadDistance) {
            this._isUpdating = true;
            this._currPage++;
            this.getNextPage(this._currPage, this._viewId);
        }
    },
    getNextPage : function(pageIdx, viewId) {
        if (pageIdx <= this._totalPages) {
            if (pageIdx < 1) {this._element.innerHTML = ''; pageIdx=1;}
            this._currPage = pageIdx;
            this._viewId = viewId;
            Element.show(this._loader);
            var params = "page=" + pageIdx + "&viewId=" + viewId;
            new Ajax.Request(this._url, {parameters:params, onComplete:this.showPageData.bind(this), evalScripts:true});
        }
    },
    showPageData : function(response) {
        this._element.innerHTML += response.responseText;
        this._isUpdating = false;
        Element.hide(this._loader);
    },
    getPageHeight : function() {
        var height = (document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight);
        return parseInt(height);
    },
    getScrollHeight : function() {
      var y;
      // all except Explorer
      if (self.pageYOffset) {
          y = self.pageYOffset;
      } else if (document.documentElement && document.documentElement.scrollTop) {
          y = document.documentElement.scrollTop;
      } else if (document.body)	{
          y = document.body.scrollTop;
      }
      return parseInt(y)+this.getWindowHeight();
    },
    getWindowHeight : function() {
      if (self.innerWidth) {
        frameWidth = self.innerWidth;
        frameHeight = self.innerHeight;
      } else if (document.documentElement && document.documentElement.clientWidth) {
        frameWidth = document.documentElement.clientWidth;
        frameHeight = document.documentElement.clientHeight; 
      } else if (document.body) {
        frameWidth = document.body.clientWidth;
        frameHeight = document.body.clientHeight;
      }
      return parseInt(frameHeight);
    }

}
if (!window.Modalbox)
	var Modalbox = new Object();

Modalbox.Methods = {
	focusableElements: new Array,
	options: {
		title: "ModalBox Window", // Title of the ModalBox window
		overlayClose: true, // Close modal box by clicking on overlay
		width: 500, // Default width in px
		height: 90, // Default height in px
		overlayOpacity: .75, // Default overlay opacity
		overlayDuration: .50, // Default overlay fade in/out duration in seconds
		slideDownDuration: .75, // Default Modalbox appear slide down effect in seconds
		slideUpDuration: .35, // Default Modalbox hiding slide up effect in seconds
		resizeDuration: .35, // Default resize duration seconds
		inactiveFade: true, // Fades MB window on inactive state
		loadingString: "Please wait. Loading...", // Default loading string message
		closeString: "Close window", // Default title attribute for close window link
		params: {},
		method: 'get' // Default Ajax request method
	},
	_options: new Object,
	
	setOptions: function(options) {
		Object.extend(this.options, options || {});
	},
	
	_init: function(options) {
		// Setting up original options with default options
		Object.extend(this._options, this.options);
		this.setOptions(options);
		//Create the overlay
		this.MBoverlay = Builder.node("div", { id: "MB_overlay", opacity: "0" });
		//Create the window
		this.MBwindow = Builder.node("div", {id: "MB_window", style: "display: none"}, [
			this.MBframe = Builder.node("div", {id: "MB_frame"}, [
				this.MBheader = Builder.node("div", {id: "MB_header"}, [
					this.MBcaption = Builder.node("div", {id: "MB_caption"}),
					this.MBclose = Builder.node("a", {id: "MB_close", title: this.options.closeString, href: "#"}, [
						Builder.build("<span>&times;</span>"),
					]),
				]),
				this.MBcontent = Builder.node("div", {id: "MB_content"}, [
					this.MBloading = Builder.node("div", {id: "MB_loading"}, this.options.loadingString),
				]),
			]),
		]);
		// Inserting into DOM
		document.body.insertBefore(this.MBwindow, document.body.childNodes[0]);
		document.body.insertBefore(this.MBoverlay, document.body.childNodes[0]);
		
		// Initial scrolling position of the window. To be used for remove scrolling effect during ModalBox appearing
		this.initScrollX = window.pageXOffset || document.body.scrollLeft || document.documentElement.scrollLeft;
		this.initScrollY = window.pageYOffset || document.body.scrollTop || document.documentElement.scrollTop;
		
		//Adding event observers
		this.hide = this.hide.bindAsEventListener(this);
		this.close = this._hide.bindAsEventListener(this);
		this.kbdHandler = this.kbdHandler.bindAsEventListener(this);
		this._initObservers();

		this.initialized = true; // Mark as initialized
		this.active = true; // Mark as active
	},
	
	show: function(content, options) {
		if(!this.initialized) this._init(options); // Check for is already initialized
		
		this.content = content;
		this.setOptions(options);
		
		Element.update(this.MBcaption, this.options.title); // Updating title of the MB
		
		if(this.MBwindow.style.display == "none") { // First modal box appearing
			this._appear();
			this.event("onShow"); // Passing onShow callback
		}
		else { // If MB already on the screen, update it
			this._update();
			this.event("onUpdate"); // Passing onUpdate callback
		} 
	},
	
	hide: function(options) { // External hide method to use from external HTML and JS
		if(this.initialized) {
			if(options) Object.extend(this.options, options); // Passing callbacks
			Effect.SlideUp(this.MBwindow, { duration: this.options.slideUpDuration, afterFinish: this._deinit.bind(this) } );
		} else throw("Modalbox isn't initialized");
	},
	
	_hide: function(event) { // Internal hide method to use inside MB class
		if(event) Event.stop(event);
		this.hide();
	},
	
	_appear: function() { // First appearing of MB
		this._toggleSelects();
		this._setOverlay();
		this._setWidth();
		this._setPosition();
		new Effect.Fade(this.MBoverlay, {
				from: 0, 
				to: this.options.overlayOpacity, 
				duration: this.options.overlayDuration, 
				afterFinish: function() {
					new Effect.SlideDown(this.MBwindow, {
						duration: this.options.slideDownDuration, 
						afterFinish: function(){ 
							this._setPosition(); 
							this.loadContent();
						}.bind(this)
					});
				}.bind(this)
		});
		
		this._setWidthAndPosition = this._setWidthAndPosition.bindAsEventListener(this);
		Event.observe(window, "resize", this._setWidthAndPosition);
	},
	
	resize: function(byWidth, byHeight, options) { // Change size of MB without loading content
		var wHeight = Element.getHeight(this.MBwindow);
		var hHeight = Element.getHeight(this.MBheader);
		var cHeight = Element.getHeight(this.MBcontent);
		var newHeight = ((wHeight - hHeight + byHeight) < cHeight) ? (cHeight + hHeight - wHeight) : byHeight;
		this.setOptions(options); // Passing callbacks
		new Effect.ScaleBy(this.MBwindow, byWidth, newHeight, {
				duration: this.options.resizeDuration, 
			  	afterFinish: function() { this.event("afterResize") }.bind(this) // Passing callback
			});
	},
	
	_update: function() { // Updating MB in case of wizards
		this.currentDims = [this.MBwindow.offsetWidth, this.MBwindow.offsetHeight];
		if((this.options.width + 10 != this.currentDims[0]) || (this.options.height + 5 != this.currentDims[1]))
			new Effect.ScaleBy(this.MBwindow, 
				(this.options.width - this.currentDims[0]), //New width calculation
				(this.options.height - this.currentDims[1]), //New height calculation
			{
				duration: this.options.resizeDuration, 
				afterFinish: this._loadAfterResize.bind(this), 
				beforeStart: function(effect) { 
					Element.update(this.MBcontent, "");
					this.MBcontent.appendChild(this.MBloading);
					Element.update(this.MBloading, this.options.loadingString);
				}.bind(this) 
			});
		else {
			Element.update(this.MBcontent, "");
			this.MBcontent.appendChild(this.MBloading);
			Element.update(this.MBloading, this.options.loadingString);
			this._loadAfterResize();
		}
	},
	
	loadContent: function () {
		if(this.event("beforeLoad") != false) { // If callback passed false, skip loading of the content
			if(typeof this.content == 'string') {
				
				var htmlRegExp = new RegExp(/<\/?[^>]+>/gi);
				if(htmlRegExp.test(this.content)) // Plain HTML given as a parameter
					this._insertContent(this.content);
					
				else new Ajax.Request( this.content, { method: this.options.method.toLowerCase(), parameters: this.options.params, 
						onComplete: function(transport) {
							var response = new String(transport.responseText);
							response.extractScripts().map(function(script) { 
								return eval(script.replace("<!--", "").replace("// -->", ""));
							}.bind(window));
							this._insertContent(transport.responseText.stripScripts());
						}.bind(this)
					});
					
			} else if (typeof this.content == 'object') {// HTML Object is given
				this._insertContent(this.content);
			} else {
				Modalbox.hide();
				throw('Please specify correct URL or HTML element (plain HTML or object)');
			}
		}
	},
	
	_insertContent: function(content){
		Element.extend(this.MBcontent);
		this.MBcontent.update("");
		if(typeof content == 'string') {
			//this.MBcontent.hide()
			//if(console.log){console.log(this.MBcontent.getHeight())};
			this.MBcontent.hide().update(content);
			//if(console.log){console.log(this.MBcontent.getHeight())};
			//this.MBcontent.show();
		}
		else if (typeof this.content == 'object') { // HTML Object is given
			var _htmlObj = content.cloneNode(true); // If node already a part of DOM we'll clone it
			if(this.content.id) _htmlObj.id = "MB_" + _htmlObj.id; // If clonable element has ID attribute defined, modifying it to prevent duplicates
			this.MBcontent.hide().appendChild(_htmlObj);
			this.MBcontent.down().show(); // Toggle visibility for hidden nodes
		}
		// Prepare and resize modal box for content
		if(this.options.height == this._options.height)
			Modalbox.resize(0, this.MBcontent.getHeight() - Element.getHeight(this.MBwindow) + Element.getHeight(this.MBheader), {
				afterResize: function(){
					this.MBcontent.show();
					this.focusableElements = this._findFocusableElements();
					this._moveFocus(); // Setting focus on first 'focusable' element in content (input, select, textarea, link or button)
					this.event("afterLoad"); // Passing callback
				}.bind(this)
			});
		else { // Height is defined. Creating a scrollable window
			this._setWidth();
			this.MBcontent.setStyle({overflow: 'auto', height: Element.getHeight(this.MBwindow) - Element.getHeight(this.MBheader) - 13 + 'px'});
			this.MBcontent.show();
			this.focusableElements = this._findFocusableElements();
			this._moveFocus(); // Setting focus on first 'focusable' element in content (input, select, textarea, link or button)
			this.event("afterLoad"); // Passing callback
		}
		
	},
	
	activate: function(options){
		this.setOptions(options);
		this.active = true;
		Event.observe(this.MBclose, "click", this.close);
		if(this.options.overlayClose) Event.observe(this.MBoverlay, "click", this.hide);
		Element.show(this.MBclose);
		if(this.options.inactiveFade) new Effect.Appear(this.MBwindow, {duration: this.options.slideUpDuration});
	},
	
	deactivate: function(options) {
		this.setOptions(options);
		this.active = false;
		Event.stopObserving(this.MBclose, "click", this.close);
		if(this.options.overlayClose) Event.stopObserving(this.MBoverlay, "click", this.hide);
		Element.hide(this.MBclose);
		if(this.options.inactiveFade) new Effect.Fade(this.MBwindow, {duration: this.options.slideUpDuration, to: .75});
	},
	
	_initObservers: function(){
		Event.observe(this.MBclose, "click", this.close);
		if(this.options.overlayClose) Event.observe(this.MBoverlay, "click", this.hide);
		Event.observe(document, "keypress", Modalbox.kbdHandler );
	},
	
	_removeObservers: function(){
		Event.stopObserving(this.MBclose, "click", this.close);
		if(this.options.overlayClose) Event.stopObserving(this.MBoverlay, "click", this.hide);
		Event.stopObserving(document, "keypress", Modalbox.kbdHandler );
	},
	
	_loadAfterResize: function() {
		this._setWidth();
		this._setPosition();
		this.loadContent();
	},
	
	_moveFocus: function() { // Setting focus to be looped inside current MB
		if(this.focusableElements.length > 0)
			this.focusableElements.first().focus(); // Focus on first focusable element except close button
		else
			$("MB_close").focus(); // If no focusable elements exist focus on close button
	},
	
	_findFocusableElements: function(){ // Collect form elements or links from MB content
		return $A($("MB_content").descendants()).findAll(function(node){
			return (["INPUT", "TEXTAREA", "SELECT", "A", "BUTTON"].include(node.tagName));
		});
	},
	
	kbdHandler: function(e) {
		var node = Event.element(e);
		switch(e.keyCode) {
			case Event.KEY_TAB:
				if(Event.element(e) == this.focusableElements.last()) {
					Event.stop(e);
					this._moveFocus();  // Find last element in MB to handle event on it. If no elements found, uses close ModalBox button
				}
			break;			
			case Event.KEY_ESC:
				if(this.active) this._hide(e);
			break;
			case 32:
				this._preventScroll(e);
			break;
			case 0: // For Gecko browsers compatibility
				if(e.which == 32) this._preventScroll(e);
			break;
			case Event.KEY_UP:
			case Event.KEY_DOWN:
			case Event.KEY_PAGEDOWN:
			case Event.KEY_PAGEUP:
			case Event.KEY_HOME:
			case Event.KEY_END:
				// Safari operates in slightly different way. This realization is still buggy in Safari.
				if(/Safari|KHTML/.test(navigator.userAgent) && !["textarea", "select"].include(node.tagName.toLowerCase()))
					Event.stop(e);
				else if( (node.tagName.toLowerCase() == "input" && ["submit", "button"].include(node.type)) || (node.tagName.toLowerCase() == "a") )
					Event.stop(e);
			break;
		}
	},
	
	_preventScroll: function(event) { // Disabling scrolling by "space" key
		if(!["input", "textarea", "select", "button"].include(Event.element(event).tagName.toLowerCase())) 
			Event.stop(event);
	},
	
	_deinit: function()
	{	
		this._toggleSelects(); // Toggle back 'select' elements in IE
		this._removeObservers();
		Event.stopObserving(window, "resize", this._setWidthAndPosition );
		Effect.toggle(this.MBoverlay, 'appear', {duration: this.options.overlayDuration, afterFinish: this._removeElements.bind(this) });
		Element.setStyle(this.MBcontent, {overflow: '', height: ''});
	},
	
	_removeElements: function () {
		if (navigator.appVersion.match(/\bMSIE\b/)) {
			this._prepareIE("", ""); // If set to auto MSIE will show horizontal scrolling
			window.scrollTo(this.initScrollX, this.initScrollY);
		}
		Element.remove(this.MBoverlay);
		Element.remove(this.MBwindow);
		this.initialized = false;
		this.event("afterHide"); // Passing afterHide callback
		this.setOptions(this._options); //Settings options object into intial state
	},
	
	_setOverlay: function () {
		if (navigator.appVersion.match(/\bMSIE\b/)) {
			this._prepareIE("100%", "hidden");
			if (!navigator.appVersion.match(/\b7.0\b/)) window.scrollTo(0,0); // Disable scrolling on top for IE7
		}
	},
	
	_setWidth: function () { //Set size
		Element.setStyle(this.MBwindow, {width: this.options.width + "px", height: this.options.height + "px"});
	},
	
	_setPosition: function () {
		this.MBwindow.style.left = Math.round((Element.getWidth(document.body) - Element.getWidth(this.MBwindow)) / 2 ) + "px";
	},
	
	_setWidthAndPosition: function () {
		this._setWidth();
		this._setPosition();
	},
	
	_getScrollTop: function () { //From: http://www.quirksmode.org/js/doctypes.html
		var theTop;
		if (document.documentElement && document.documentElement.scrollTop)
			theTop = document.documentElement.scrollTop;
		else if (document.body)
			theTop = document.body.scrollTop;
		return theTop;
	},
	// For IE browsers -- IE requires height to 100% and overflow hidden (taken from lightbox)
	_prepareIE: function(height, overflow){
		var body = document.getElementsByTagName('body')[0];
		body.style.height = height;
		body.style.overflow = overflow;
  
		var html = document.getElementsByTagName('html')[0];
		html.style.height = height;
		html.style.overflow = overflow; 
	},
	// For IE browsers -- hiding all SELECT elements
	_toggleSelects: function() {
		if (navigator.appVersion.match(/\bMSIE\b/))
			$$("select").each( function(select) { 
				select.style.visibility = (select.style.visibility == "") ? "hidden" : "";
			});
	},
	event: function(eventName) {
		if(this.options[eventName]) {
			var returnValue = this.options[eventName](); // Executing callback
			this.options[eventName] = null; // Removing callback after execution
			if(returnValue != undefined) 
				return returnValue;
			else 
				return true;
		}
		return true;
	}
}

Object.extend(Modalbox, Modalbox.Methods);

Effect.ScaleBy = Class.create();
Object.extend(Object.extend(Effect.ScaleBy.prototype, Effect.Base.prototype), {
  initialize: function(element, byWidth, byHeight, options) {
    this.element = $(element)
    var options = Object.extend({
	  scaleFromTop: true,
      scaleMode: 'box',        // 'box' or 'contents' or {} with provided values
      scaleByWidth: byWidth,
	  scaleByHeight: byHeight
    }, arguments[3] || {});
    this.start(options);
  },
  setup: function() {
    this.elementPositioning = this.element.getStyle('position');
      
    this.originalTop  = this.element.offsetTop;
    this.originalLeft = this.element.offsetLeft;
	
    this.dims = null;
    if(this.options.scaleMode=='box')
      this.dims = [this.element.offsetHeight, this.element.offsetWidth];
	 if(/^content/.test(this.options.scaleMode))
      this.dims = [this.element.scrollHeight, this.element.scrollWidth];
    if(!this.dims)
      this.dims = [this.options.scaleMode.originalHeight,
                   this.options.scaleMode.originalWidth];
	  
	this.deltaY = this.options.scaleByHeight;
	this.deltaX = this.options.scaleByWidth;
  },
  update: function(position) {
    var currentHeight = this.dims[0] + (this.deltaY * position);
	var currentWidth = this.dims[1] + (this.deltaX * position);
	
    this.setDimensions(currentHeight, currentWidth);
  },

  setDimensions: function(height, width) {
    var d = {};
    d.width = width + 'px';
    d.height = height + 'px';
    
	var topd  = Math.round((height - this.dims[0])/2);
	var leftd = Math.round((width  - this.dims[1])/2);
	if(this.elementPositioning == 'absolute' || this.elementPositioning == 'fixed') {
		if(!this.options.scaleFromTop) d.top = this.originalTop-topd + 'px';
		d.left = this.originalLeft-leftd + 'px';
	} else {
		if(!this.options.scaleFromTop) d.top = -topd + 'px';
		d.left = -leftd + 'px';
	}
    this.element.setStyle(d);
  }
});

var TokenMgr = Class.create();
TokenMgr.prototype = {
    _token : '',
    initialize : function() {
        this.fetchToken();
    },
    fetchToken : function() {
        new Ajax.Request('/ajax/token.aspx',{asynchronous: false, onComplete: this.complete.bind(this)});
    },
    getToken : function() {
        return this._token;
    },
    complete : function(response) {
        this._token = response.responseText;
    }
}