// add class "jsEnabled" to body tag for JS-enabled browsers
document.documentElement.className = 'jsEnabled';

// polling interval for custom resize event
jQuery.resize.delay = 100;

var kg = {};

kg.isIE6 = /MSIE 6/.test(navigator.userAgent);
kg.isIE7 = /MSIE 7/.test(navigator.userAgent);

/*
* Box utility methods: 
* Get inner and outer dimensions.
* Set Box Height.
*/
kg.box = {
	/*
	* Get the size of the box's content area.
	* @param boxID {String} ID of box to measure.
	*/
	getInnerSize: function(boxID) {
		var thisBoxMiddle = $('#' + boxID + ' .midMiddle:first');
		var thisBoxInnerW = thisBoxMiddle.width(), thisBoxInnerH = thisBoxMiddle.height();
		return {
			'width': thisBoxInnerW,
			'height': thisBoxInnerH
		}
	},
	/*
	* Get the overall size of the box.
	* @param boxID {String} ID of box to measure.
	*/
	getOuterSize: function(boxID) {
		var thisBox = $('#' + boxID);
		var thisBoxTL = thisBox.find('.topLeft').first();
		var thisBoxOuterW = thisBoxTL.width() + thisBox.find('.topMiddle').first().width() + thisBox.find('.topRight').first().width();
		var thisBoxOuterH = thisBoxTL.height() + thisBox.find('.midLeft').first().height() + thisBox.find('.btmLeft').first().height();
		return {
			'width': thisBoxOuterW,
			'height': thisBoxOuterH
		}
	},
	/*
	* Set the box height based on content height
	* @param boxID {String} ID of box
	*/
	setBoxHeight: function(boxID) {
		var boxHeight = $('#'+boxID+' .content').height();
		$('#'+boxID+' .boxH').css('height', boxHeight+'px');
	}
}

/* 
* Fix Min Width for Footer in IE6
*/
kg.fixIE6MinWidth = (function() {
	function _init() {
		if(kg.isIE6){
			_adjustMinWidthFooter();
			$(window).bind('resize', function() {
				_adjustMinWidthFooter()
			});
		}
	}
	function _adjustMinWidthFooter(){
		if ($('body').width() < 1003) {
			$('#footer').css('width', '1002px');
		} else {
			$('#footer').css('width', '100%');
		}
	}
	return {
		init: _init
	}
})();

/*
* Fix Section Gradient for IE6 and IE7
*/
kg.fixGradientIE6AndIE7 = (function() {
	function _init() {
		if (kg.isIE6 || kg.isIE7) {
			$('#pageGradient').css('zoom', '1');
			$('#shoppingGradient').css('zoom', '1');
			$('#profileGradient').css('zoom', '1');
			$('#contactGradient').css('zoom', '1');
			$('#siteMapGradient').css('zoom', '1');
			$('.editItemGradient').css('zoom', '1');
		} 
	}
	return {
		init: _init
	}
})();

/*
* Handle hovering over header links, top menu bar items, and footer links
*/
kg.itemHover = (function() {
	function _init() {
		$('.menu li a').hover(_hoverLink, _unhoverLink);
		$('.footerCatLinks li a').hover(_hoverLink, _unhoverLink);
		$('#headerLinks ul li').hover(_hoverLink, _unhoverLink);
	}
	function _hoverLink() {
		$(this).addClass('itemHover');
	}
	function _unhoverLink() {
		$(this).removeClass('itemHover');
	}
	return {
		init: _init
	}
})();

/*
* Nav menu object.
* @param element {Object} jQuery object for nav link item.
*/
kg.navMenuItem = function(element) {
	// scope var
	var item = this;
	// item object properties
	this.element = element;
	//this.navElements = this.element.add(this.element.prev()).add(this.element.next());
	this.number = this.element.get(0).id.substring(4);
	//this.menuContent = $('#menu' + this.number, '#menus');
	this.menuContent = $('#menu' + this.number);
	this.hasMenu = this.menuContent.length;
	this.pos = this.element.offset();
	this.topPos = this.pos.top;
	this.leftPos = this.pos.left;
	this.overItem = false;
	this.checkOverTimer = null;
	// if item has an associated menu...
	if (this.hasMenu) {
		this.overMenu = false;
		this.menuBox = $($('#navMenuTemplate').get(0).cloneNode(true));
		this.menuBoxID = 'menuBox' + this.number; 
		// clone template node
		// set box id and insert before content area
		this.menuBox.get(0).id = item.menuBoxID;
		this.menuBox
			.removeClass('template')
			.addClass('menuBox')
			//.appendTo('#menus')
			.appendTo('#header .inner')
			.find('.contentPlaceholder')
			.replaceWith(item.menuContent.css({
				'display': 'block',
				'position': 'static'
			}));
		$('#'+item.menuBoxID).bgiframe();
		// show and move to left to calculate dimensions, then hide and move to default pos again
		this.menuBox.css('left', '-5000px').show();
		var menuBoxSize = kg.box.getInnerSize(item.menuBoxID);
		this.menuBox.find('.boxW').css('width', menuBoxSize.width + 10 + 'px');
		this.menuBox.css('width', menuBoxSize.width + 10 + 120 + 'px'); // For IE6 compatibility
		this.menuBox.find('.boxH').css('height', menuBoxSize.height + 'px');
		this.menuBox.hide().css('left', 'auto');
	}
	this.element.hover(
		function() { item.doItemOver(); },
		function() { item.doItemOff(); }
	);
	// item object methods
	this.doItemOver = function() {
		var element = item.element;
		item.overItem = true;
		// show item on state	
		element.children('div').addClass('navOver');

		// if there's a menu, show it and set up its handlers
		if (item.hasMenu) {
			var menuBox = item.menuBox;
			item.posMenu();
			
			menuBox.show();
			menuBox.hover(
				item.doMenuOver,
				item.doMenuOff
			);
			if (kg.isIE6) {
				// IEPNGFix.update();
				menuBox.find('.midLeft,.midRight,.btmRight,.btmMiddle,.btmLeft').addClass('transparent');
			}				
		}
	}
	this.doItemOff = function() {
		item.overItem = false;
		// timer for checking over status
		item.setCheckOverTimer();
	}
	this.doMenuOver = function() {
		item.overMenu = true;
	}
	this.doMenuOff = function() {
		item.overMenu = false;
		item.setCheckOverTimer();		
	}
	// show off state of item and hide menu
	this.doBothOff = function() {
		element.children('div').removeClass('navOver');
		if (item.hasMenu) {
			item.menuBox.hide();
		}
	}
	this.setCheckOverTimer = function() {
		item.checkOverTimer = setTimeout(function() {
			item.checkOver();
		}, 50);
	}
	// see if user is still over nav item or menu
	this.checkOver = function() {
		var overCriterion = item.hasMenu ? (item.overItem === false && item.overMenu === false) : (item.overItem === false);
		if (overCriterion) {
			clearTimeout(item.checkOverTimer);
			item.doBothOff();
		}
	}
	// get item location and position menu below it
	this.posMenu = function() {
		item.menuBox.css({
			//'top': (item.topPos - (item.element.height() * 2)) + 'px',
			'top': item.topPos + item.element.height() - 4 + 'px',
			'left': item.element.offset().left - 40 + 'px'
		});
	}
	
}

/*
* Nav box (non-menu) object.
* @param {String} prefix Unique prefix used w/link and box IDs. 
*/
kg.navBoxItem = function(prefix) {
	/*
	* Define properties.
	*/
	var boxItem = this;
	this.boxLPos;
	this.boxW;
	this.linkSel = '#' + prefix + 'Link';
	this.boxSel = '#' + prefix + 'Box';
	this.link = $(this.linkSel);
	this.box = $(this.boxSel);
	this.boxID = this.box.get(0).id;
	/* 
	* Get left position for box.
	* Use different calculations for different boxes/box IDs.
	*/
	this.getBoxPosition = function() {
		var thisBoxLPos;
		var thisBoxID = boxItem.boxID;
		var winW = $(window).width()
		// center mini cart box in window if window is narrower than page
		if ((winW < $('#header .inner').width()) && (thisBoxID === 'miniCartBox')) {
			thisBoxLPos = winW - boxItem.boxW;
		} else {
			if (thisBoxID === 'orderStatusBox') {
				thisBoxLPos = ($(window).width() - boxItem.boxW)/2;
			} else if (thisBoxID === 'miniCartBox') {
				var checkoutBtn = $('#checkoutBtn');
				thisBoxLPos = (checkoutBtn.offset().left + checkoutBtn.width() - boxItem.boxW);
			} 
		}
		return thisBoxLPos;
	}
	/*
	* Position header boxes (order status, mini cart).
	* Some values of width, height, top, left are hard-coded in CSS.
	* Some values are calculated.
	*/
	this.showBox = function() {
		var thisBox = boxItem.box;
		var thisBoxID = boxItem.boxID;
		kg.overlayBG.show();
		// position then show box
		thisBox.css('left', this.boxLPos + 'px')
			.show();
		if (kg.isIE6) {
			IEPNGFix.update();
		}
		thisBox.find('.closeBox').bind('click', boxItem.closeBox);
	}
	/*
	* Close the box.
	*/
	this.closeBox = function() {
		kg.overlayBG.hide();
		boxItem.box.hide();
	}
	/*
	* Reposition boxes that are open.
	*/
	this.repositionBox = function() {
		var thisBox = boxItem.box;
		this.boxLPos = boxItem.getBoxPosition();
		if (thisBox.css('display') == 'block') {
			thisBox.css('left', this.boxLPos);
		}
	}
	/*
	* Initialize object.
	*/
	this.init = function() {
		var thisBox = boxItem.box
		var thisBoxID = boxItem.boxID;
		thisBox.show();
		thisBox.bgiframe();		
		boxItem.boxW = kg.box.getOuterSize(thisBoxID).width;
		boxItem.boxLPos = boxItem.getBoxPosition();
		if (thisBoxID === 'miniCartBox') {
			thisBox.find('.boxH').css('height', kg.box.getInnerSize(thisBoxID).height + 'px');
			if (kg.isIE6 || kg.isIE7) {
				thisBox.css('height', kg.box.getInnerSize(thisBoxID).height + 50 + 50 + 'px')
				thisBox.find('.boxW').css('width', kg.box.getInnerSize(thisBoxID).width + 'px');
				thisBox.css('width', kg.box.getInnerSize(thisBoxID).width + 50 + 50 + 'px')
			}
		} else if (thisBoxID === 'orderStatusBox') {
			thisBox.css('width', kg.box.getInnerSize(thisBoxID).width + 120 + 'px');
		}
		thisBox.hide();
		// event handlers
		boxItem.link.bind('click', function(e) {
			e.preventDefault();
			boxItem.showBox();
		});
		$(window).bind('resize', function() {
			boxItem.repositionBox();
		});
	}
	this.init();	
}

/* 
* Manager to create and handle all nav item objects.
* @requires jquery.ba-resize.js
*/
kg.navManager = (function() {
	var _menuItems, _menuItems, _menuItemsLen;
	var _boxItemIDs = []
	var _boxItems = [];
	var _boxItemIDsLen, _boxItemsLen;
	function _init() {
		_menuItems = $('#nav .item');
		_menuItems = _menuItems.toArray();
		_menuItemsLen = _menuItems.length;
		_boxItemIDs = ['orderStatus', 'miniCart'];
		_boxItemIDsLen = _boxItemIDs.length;
		_createItemObjects();
		$(window).bind('resize', function() {
			// _reCreateItemObjects();
		});
	}
	function  _reCreateItemObjects(){
		
	}
	/*
	* Create menu and box item objects.
	*/
	function _createItemObjects() {
		// menu items
		for (var i=0; i < _menuItemsLen; i++) {
			var thisMenuItem = new kg.navMenuItem($(_menuItems[i]));
		};
		// box items
		for (var i=0; i < _boxItemIDsLen; i++) {
			var thisNavItem = new kg.navBoxItem(_boxItemIDs[i]);
			_boxItems.push(thisNavItem);
		};
		_boxItemsLen = _boxItems.length;
	}
	return {
		init: _init
	}
})();

/*
* Utility method to open modal dialogs.
* @requires jquery.simplemodal-1.3.5.min.js
* @requires dimensions.tool.js
*/
kg.modalDialogManager = (function(containerID, contentID) {
    function _openModal(modalID, options) {
        var theseOptions = $.extend({
            onShow: function(dialog) {
				if (kg.isIE6) {
					dialog.data.find('.topRight,.topMiddle,.topLeft,.midLeft,.midRight,.btmRight,.btmMiddle,.btmLeft').addClass('transparent');
				}
            },
			position: null,
			absolute: false,
			onOpen: function(dialog) {
				//place holder
			}
        }, options || {});
        $('#' + modalID).modal({
            opacity: 01,
			autoPosition: !theseOptions.absolute,
			position: theseOptions.position,
			containerCss: (!theseOptions.position && theseOptions.absolute) ? {position: 'absolute'} : {},
            onShow: theseOptions.onShow,
            onOpen: function(dialog) {
                dialog.overlay.show();
                dialog.container.show();
                dialog.data.show();
				if (theseOptions.absolute) {
					sb_windowTools.centerElementOnScreen($("#simplemodal-container"));
				}
				theseOptions.onOpen(dialog);
				// uncomment below to trigger a modal onOpen event that can be listened for
                // $(window).trigger('mdm:opened');
            },
            onClose: function(dialog) {
                dialog.data.hide();
                dialog.container.hide();
                dialog.overlay.hide();
                $.modal.close();
                // uncomment below to trigger a modal onOpen event that can be listened for
                // $(window).trigger('mdm:opened');
            }
        });
    }
    return {
        openModal: function(modalID, options) {
            _openModal(modalID, options);
        },
		init: function() {
			$(window).bind('resize', function(){
				sb_windowTools.centerElementOnScreen($("#simplemodal-container"));
			});
		}
    };
})();


/**
 * Set Profile Box Heights
 **/
kg.profileBoxes = (function() {
	function _setTabBoxHeight(tabBox) {
		var tabBoxHeight = $(tabBox+' .content').height() + 20 + 40; // + Content top and bottom margins
		$(tabBox+' .boxH').css('height', tabBoxHeight+'px');	
	}
	function _setWrapperBoxHeight(wrapperBox) {
		var wrapperHeight = $(wrapperBox+' .wContent').height() + 18 + 13; // + Content top and bottom margins
		$(wrapperBox+' .wBoxH').css('height', wrapperHeight+'px');
	}
	return {
		setProfileBoxHeights: function(tabBox) {
			_setTabBoxHeight(tabBox);
			_setWrapperBoxHeight('.profileWrapperBox');
		}
	}
})();

/**
 * Set Store Box Heights
 **/
kg.storeBox = (function() {
	function _setBoxHeight(overlayID) {
		var overlayBoxHeight = $('#'+overlayID+' .content').height() + 30 + 30; // + Content top and bottom margins
		$('#'+overlayID+' .boxH').css('height', overlayBoxHeight+'px');
		$('#'+overlayID).css('height', overlayBoxHeight+5+5+'px'); // For IE6 and IE7
	}
	return {
		setBoxHeight: function(overlayID) {
			_setBoxHeight(overlayID);
		}
	}
})();

/**
 * Set Overlay Box Heights
 **/
kg.overlayBox = (function() {
	function _setBoxHeight(overlayID) {
		var overlayBoxHeight = $('#'+overlayID+' .content').height();
		$('#'+overlayID+' .boxH').css('height', overlayBoxHeight+'px');
		$('#'+overlayID).css('height', overlayBoxHeight+50+50+'px'); // For IE6 and IE7
	}
	return {
		setBoxHeight: function(overlayID) {
			_setBoxHeight(overlayID);
		}
	}
})();

kg.overlayBG = (function() {
	function _show() {
		_setWidthAndHeight();
		$('#overlayBG').show()
	}
	function _hide() {
		$('#overlayBG').hide();
	}
	function _setWidthAndHeight() {
		$('#overlayBG').css('height', $(document).height()+'px');
		$('#overlayBG').css('width', $(window).width()+'px');
	}
	return {
		show: function() {
			_show();
		},
		hide: function() {
			_hide();
		}
	}
})();

kg.emailUpdates = (function() {
	function _init(){
		_addLinkHandler();
		_addUpdatesSubmitHandler();
	}
	function _addUpdatesSubmitHandler() {
		$('#submitEmailUpdates').click(function(e) {
			e.preventDefault();			
			$('#emailUpdatesForm').submit();
		});
	}
	function _addLinkHandler(){
		$('#emailUpdatesLink').click(function(e) {
	        e.preventDefault();
	        kg.modalDialogManager.openModal('emailUpdatesModal', {
				onShow: function(dialog) {
					_emailUpdatesValidation();
					if (kg.isIE6) {
						dialog.data.find('.topRight,.topMiddle,.topLeft,.midLeft,.midRight,.btmRight,.btmMiddle,.btmLeft').addClass('transparent');
					}
				},
				onOpen: function(dialog) {			
					kg.overlayBox.setBoxHeight('emailUpdatesModal');
				}
			});
		});
	}
	function _emailUpdatesValidation() {
		if ($('#emailUpdatesForm').length) {

	        $('#emailUpdatesForm').validate({
				errorClass: "formError",
	            ignoreTitle: true,
				highlight: function(element, errorClass) {
					$(element).addClass(errorClass);
					$(element).prev().addClass('error');
					if ($(element).parent().find('.helperText').length) {
						$(element).parent().find('.helperText').css('top','35px');
					}
					if (!$(element).parent().find('div.clearError').length) {
						$(element).prev().before("<div class='clearError'><!-- --></div>");
					}
				},
				unhighlight: function(element, errorClass) {
					$(element).removeClass(errorClass);
					$(element).prev().removeClass('error');
					if ($(element).parent().find('.helperText').length) {
						$(element).parent().find('.helperText').css('top','20px');
					}
					$(element).parent().find('div.clearError').remove();
				},
				submitHandler: function(form) {
					ajaxEmailOptIn(form);					
				},
				invalidHandler: function(form, validator) {
					var errors = validator.numberOfInvalids();
				    if (errors) {
				        $("#emailUpdatesForm div.formErrorNotice").show();
				      } else {
				        $("#emailUpdatesForm div.formErrorNotice").hide();
				      }
				},
				showErrors: function(errorMap, errorList) {
					kg.overlayBox.setBoxHeight('emailUpdatesModal');
					this.defaultShowErrors();
				},
	            errorPlacement: function(e, el) {
	                e.prependTo(el.parent());
	                kg.overlayBox.setBoxHeight('emailUpdatesModal');
	            },
	            rules: {
	                emailUpdatesEmail: { required: true, email: true }
	            }
	        });
		}
	}
	return {
		init: function(){
			_init();
		}
	}
})();


function ajaxEmailOptIn(form) {
    var EmailOptInAction = document.getElementById("EmailOptInAction").value; 
    var emailUpdatesEmailInput=document.getElementById("emailUpdatesEmail").value
	var ajaxRequest; // The variable that makes Ajax possible!	
	
	try{
	// Opera 8.0+, Firefox, Safari
		ajaxRequest = new XMLHttpRequest();
	} catch (e){
	// Internet Explorer Browsers
	try{
	ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
	} catch (e) {
	try{
		ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
	} catch (e){
	// Something went wrong
	alert("You Browser would not support Ajax");
	return false;
	}
	}
	}
	// Create a function that will receive data sent from the server
	ajaxRequest.onreadystatechange = function(){
		if(ajaxRequest.readyState == 4){
			$.modal.close();
			kg.modalDialogManager.openModal('emailUpdatesConfirmModal', {
				onOpen: function(dialog) {
					var boxHeight = $('#emailUpdatesConfirmModal .content').height() + 45;
					$('#emailUpdatesConfirmModal .boxH').css('height', boxHeight+'px');
				}
			});
			var msg = ajaxRequest.responseText;
			//alert(msg);
			if(msg == "true" || msg == ""){
				$("#emailUpdatesConfirmText").text("Thanks! You will begin receiving exclusive sales and promotions emails from K&G at " + form.emailUpdatesEmail.value + ".");
			}else{
				$("#emailUpdatesConfirmText").text("The email " + form.emailUpdatesEmail.value + " is already registered with us.");
			}
		}
	} 
	ajaxRequest.open("GET", EmailOptInAction+"&emailUpdatesEmail="+emailUpdatesEmailInput, true);
	ajaxRequest.send(null); 
}

function getRequestBody(frm) {
	var data = "";
	for (var i=0 ; i < frm.elements.length; i++) {
    	data=data+frm.elements[i].name+"="+frm.elements[i].value+"&";
	}
    return data;
}

function dropdown_menu_hack(el)
{
if(!el.runtimeStyle){return;}
if(el.runtimeStyle.behavior.toLowerCase()=="none"){return;}
el.runtimeStyle.behavior="none";

var ie5 = (document.namespaces==null);
el.ondblclick = function(e)
{
window.event.returnValue=false;
return false;
}

if(window.createPopup==null)
{

var fid = "dropdown_menu_hack_" + Date.parse(new Date());

window.createPopup = function()
{
if(window.createPopup.frameWindow==null)
{
el.insertAdjacentHTML("AfterEnd","<iframe id='"+fid+"' name='"+fid+"' src='about:blank' frameborder='1' scrolling='no'></></iframe>");
var f = document.frames[fid];
f.document.open();
f.document.write("<html><body></body></html>");
f.document.close();
f.fid = fid;


var fwin = document.getElementById(fid);
fwin.style.cssText="position:absolute;top:0;left:0;display:none;z-index:99999;";


f.show = function(px,py,pw,ph,baseElement)
{
py = py + baseElement.getBoundingClientRect().top + Math.max( document.body.scrollTop, document.documentElement.scrollTop) ;
px = px + baseElement.getBoundingClientRect().left + Math.max( document.body.scrollLeft, document.documentElement.scrollLeft) ;
fwin.style.width = pw + "px";
fwin.style.height = ph + "px";
fwin.style.posLeft =px ;
fwin.style.posTop = py ;
fwin.style.display="block";
}


f_hide = function(e)
{
if(window.event && window.event.srcElement && window.event.srcElement.tagName && window.event.srcElement.tagName.toLowerCase()=="select"){return true;}
fwin.style.display="none";
}
f.hide = f_hide;
document.attachEvent("onclick",f_hide);
document.attachEvent("onkeydown",f_hide);

}
return f;
}
}

function showMenu()
{

function selectMenu(obj)
{
var o = document.createElement("option");
o.value = obj.value;
o.innerHTML = obj.innerHTML;
while(el.options.length>0){el.options[0].removeNode(true);}
el.appendChild(o);
el.title = o.innerHTML;
el.contentIndex = obj.selectedIndex ;
el.menu.hide();
}


el.menu.show(0 , el.offsetHeight , 10, 10, el);
var mb = el.menu.document.body;

mb.style.cssText ="border:solid 1px black;margin:0;padding:0;overflow-y:auto;overflow-x:auto;background:white;text-aligbn:center;font-family:Verdana;font-size:12px;";
var t = el.contentHTML;
t = t.replace(/<select/gi,'<ul');
t = t.replace(/<option/gi,'<li');
t = t.replace(/<\/option/gi,'</li');
t = t.replace(/<\/select/gi,'</ul');
mb.innerHTML = t;


el.select = mb.all.tags("ul")[0];
el.select.style.cssText="list-style:none;margin:0;padding:0;";
mb.options = el.select.getElementsByTagName("li");

for(var i=0;i<mb.options.length;i++)
{
mb.options[i].selectedIndex = i;
mb.options[i].style.cssText = "list-style:none;margin:0;padding:1px 2px;width/**/:100%;cursor:hand;cursor:pointer;white-space:nowrap;"
mb.options[i].title =mb.options[i].innerHTML;
mb.options[i].innerHTML ="<nobr>" + mb.options[i].innerHTML + "</nobr>";
mb.options[i].onmouseover = function()
{
if( mb.options.selected ){mb.options.selected.style.background="white";mb.options.selected.style.color="black";}
mb.options.selected = this;
this.style.background="#333366";
this.style.color="white";
}

mb.options[i].onmouseout = function(){this.style.background="white";this.style.color="black";}
mb.options[i].onmousedown = function(){selectMenu(this); }
mb.options[i].onkeydown = function(){selectMenu(this); }


if(i == el.contentIndex)
{
mb.options[i].style.background="#333366";
mb.options[i].style.color="white";
mb.options.selected = mb.options[i];
}
}


var mw = Math.max( ( el.select.offsetWidth + 22 ), el.offsetWidth + 22 );
mw = Math.max( mw, ( mb.scrollWidth+22) );
var mh = mb.options.length * 15 + 8 ;

var mx = (ie5)?-3:0;
var my = el.offsetHeight -2;
var docH = document.documentElement.offsetHeight ;
var bottomH = docH - el.getBoundingClientRect().bottom ;

mh = Math.min(mh, Math.max(( docH - el.getBoundingClientRect().top - 50),100) );

if(( bottomH < mh) )
{

mh = Math.max( (bottomH - 12),10);
if( mh <100 )
{
my = -100 ;

}
mh = Math.max(mh,100);
}


self.focus();

el.menu.show( mx , my , mw, mh , el);
sync=null;
if(mb.options.selected)
{
mb.scrollTop = mb.options.selected.offsetTop;
}




window.onresize = function(){el.menu.hide()};
}

function switchMenu()
{
if(event.keyCode)
{
if(event.keyCode==40){ el.contentIndex++ ;}
else if(event.keyCode==38){ el.contentIndex--; }
}
else if(event.wheelDelta )
{
if (event.wheelDelta >= 120)
el.contentIndex++ ;
else if (event.wheelDelta <= -120)
el.contentIndex-- ;
}else{return true;}




if( el.contentIndex > (el.contentOptions.length-1) ){ el.contentIndex =0;}
else if (el.contentIndex<0){el.contentIndex = el.contentOptions.length-1 ;}

var o = document.createElement("option");
o.value = el.contentOptions[el.contentIndex].value;
o.innerHTML = el.contentOptions[el.contentIndex].text;
while(el.options.length>0){el.options[0].removeNode(true);}
el.appendChild(o);
el.title = o.innerHTML;
}

if(dropdown_menu_hack.menu ==null)
{
dropdown_menu_hack.menu = window.createPopup();
document.attachEvent("onkeydown",dropdown_menu_hack.menu.hide);
}
el.menu = dropdown_menu_hack.menu ;
el.contentOptions = new Array();
el.contentIndex = el.selectedIndex;
el.contentHTML = el.outerHTML;

for(var i=0;i<el.options.length;i++)
{
el.contentOptions [el.contentOptions.length] =
{
"value": el.options[i].value,
"text": el.options[i].innerHTML
}

if(!el.options[i].selected){el.options[i].removeNode(true);i--;};
}


el.onkeydown = switchMenu;
el.onclick = showMenu;
el.onmousewheel= switchMenu;

}

// global page initialization
kg.initPage = function() {
	kg.navManager.init();
	kg.modalDialogManager.init();
	kg.emailUpdates.init();
	kg.fixIE6MinWidth.init();
	kg.fixGradientIE6AndIE7.init();
	kg.itemHover.init();
}
$(document).ready(kg.initPage);

