/**
 * @author Shea
 */
function createCookie(name,value,days) {
	var expires = "";
	if (days) {
		var date = new Date();
		date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
		expires = "; expires=" + date.toGMTString();
	}
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0) == ' ') {
			c = c.substring(1, c.length);
		}
		if (c.indexOf(nameEQ) === 0) {
			return c.substring(nameEQ.length, c.length);
		}
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}

function showDidYouKnow(force){
	if (readCookie('didYouKnow') !== 'close' || force) {
		didYouKnow1 = Ext.get('didYouKnow');
		didYouKnow1.setStyle({
			right: (Ext.get('hstopmenu').getX()+100)+'px'
		});
		didYouKnow1.slideIn('r');
	}
}

function hideDidYouKnow(){
	createCookie('didYouKnow','close');
	Ext.get('didYouKnow').switchOff();
}


    
Ext.ns('Ext.ux');

Ext.ux.SimplePop = (function(){
    var els = {};

    return {

        init: function() {
            Ext.apply(this, Ext.util.Observable.prototype);
            Ext.util.Observable.constructor.call(this);
            this.addEvents('open', 'close');
            this.initMarkup();
            this.initEvents();
        },

        initMarkup: function() {
            els.shim = Ext.DomHelper.append(document.body, {
                tag: 'iframe',
                id: 'ux-simplepop-shim'
            }, true);

            els.mask = Ext.DomHelper.append(document.body, {
                id: 'ux-simplepop-mask'
            }, true);
            
            var popTpl = new Ext.Template(this.getTemplate());
            els.pop = popTpl.append(document.body, {}, true);
            els.navClose1 = Ext.get('ux-simplepop-closeContainer1');
            els.navClose2 = Ext.get('ux-simplepop-closeContainer2');
            els.mask.visibilityMode = els.pop.visibilityMode = els.shim.visibilityMode = Ext.Element.DISPLAY;

            els.shim.hide();
            els.mask.hide();
            els.pop.hide();

        },

        getTemplate : function() {
            return [
                '<div id="ux-simplepop">',
                    '<div id="ux-simplepop-outerContainer" class="ux-simplepop-body">',
                        '<div id="ux-simplepop-closeContainer1" class="ux-simplepop-close"></div>',
                        '<div id="ux-simplepop-closeContainer2" class="ux-simplepop-close"></div>',
                    '</div>',
                '</div>'
            ];
        },

        initEvents: function() {

            els.navClose1.on('click', function(e) {
                e.preventDefault();
                e.stopPropagation();
                createCookie('chatPop','close');
                this.close();
            }, this);

            els.navClose2.on('click', function(e) {
                e.preventDefault();
                e.stopPropagation();
                createCookie('chatPop','close');
                this.close();
            }, this);
            
            els.mask.on('click', function(e) {
                e.preventDefault();
                e.stopPropagation();
                this.close();
            }, this);
            
            els.pop.on('click', function(e) {
                e.preventDefault();
                e.stopPropagation();
                launchWin('framemain','http://chat.homeandstone.com:9090/webchat/start.jsp?workgroup=hs@workgroup.chat&location='+escape(document.location.href),500, 400);
            }, this);
        },

        register: function(el) {
            this.animateTarget = Ext.get(el);
            this.animateTarget.on('click', function(e){
                e.preventDefault();
                this.open();
            }, this);
        },

        open: function(el) {
            if (!this.animateTarget){
                this.animateTarget = Ext.get(el);
            }
            var viewSize = this.getViewSize();
            els.shim.setStyle({
                width: viewSize[0] + 'px',
                height: viewSize[1] + 'px'
            }).show();

            els.mask.setStyle({
                width: viewSize[0] + 'px',
                height: viewSize[1] + 'px'
            }).show();

            els.pop.setStyle({
                position: 'absolute',
                top: this.animateTarget.getTop()+'px',
                left: this.animateTarget.getLeft()+'px'
            });

            els.pop.setWidth(this.animateTarget.getWidth());
            els.pop.setHeight(this.animateTarget.getHeight());
            els.pop.show();
            els.pop.setOpacity(0);
            els.pop.shift({
                y: 200,
                x: viewSize[0] / 2,
                width: 355,
                height: 201,
                duration: 0.75,
                easing: 'easeIn',
                opacity: 1
            });
            
            this.fireEvent('open');
        },

        close: function(){
            els.mask.hide();
            els.shim.hide();

            els.pop.setWidth(this.animateTarget.getWidth());
            els.pop.setHeight(this.animateTarget.getHeight());
            els.pop.shift({
                x: this.animateTarget.getLeft(),
                y: this.animateTarget.getTop(),
                width: this.animateTarget.getWidth(),
                height: this.animateTarget.getHeight(),
                duration: 1.75,
                easing: 'easeOut',
                opacity: 0
            });
            
            this.fireEvent('close');
        },

        getViewSize: function() {
            return [Ext.lib.Dom.getViewWidth(true), Ext.lib.Dom.getViewHeight(true)];
        }
    };
})();

Ext.ns('Ext.ux');

Ext.ux.Menu = Ext.extend(Ext.util.Observable, {
    direction: 'horizontal',
    delay: 0.2,
    autoWidth: true,
    transitionType: 'fade',
    transitionDuration: 0.3,
    animate: true,
    currentClass: 'current',

    constructor: function(elId, config) {
        config = config || {};
        Ext.apply(this, config);

        Ext.ux.Menu.superclass.constructor.call(this, config);

        this.addEvents(
            'show',
            'hide',
            'click'
        );

        this.el = Ext.get(elId);
        this.el.select('ul').removeClass('ux-menu-inithide');
        this.initMarkup();
        this.initEvents();

        this.setCurrent();
    },

    initMarkup: function(){
        this.container = this.el.up('div').setStyle('z-index',--Ext.ux.Menu.zSeed); //this.el.wrap({cls: 'ux-menu-container', style: 'z-index: ' + --Ext.ux.Menu.zSeed});
        this.items = this.el.select('li');

        this.el.addClass('ux-menu-' + this.direction);
        //this.el.select('>li').addClass('ux-menu-item-main');

        this.el.select('li:has(>ul)').addClass('ux-menu-item-parent').each(function(item) {
            item.down('a').addClass('ux-menu-link-parent ux-menu-arrow');
                //.addClass('ux-menu-link-parent');
                //.createChild({tag: 'span', cls: 'ux-menu-arrow'});
        });
        
        this.el.select('li:first-child>a').addClass('ux-menu-link-first');
        this.el.select('li:last-child>a').addClass('ux-menu-link-last');

        // create clear fixes for the floating stuff
        this.container.addClass('ux-menu-clearfix');

        // if autoWidth make every submenu as wide as its biggest child;
        if(this.autoWidth) {
            this.doAutoWidth();
        }

        var subs = this.el.select('ul');
        subs.addClass('ux-menu-sub').setStyle('z-index',++Ext.ux.Menu.zSeed);
        
        //ie6 and ie7/ie8 quirksmode need iframes behind the submenus
        if(Ext.isBorderBox || Ext.isIE7) {
            subs.each(function(item) {
                item.parent().createChild({tag: 'iframe', cls: 'ux-menu-ie-iframe'})
                    .setWidth(item.getWidth())
                    .setHeight(item.getHeight());
            });
        }
        
        subs.addClass('ux-menu-hidden');
    },

    initEvents: function() {
        this.showTask = new Ext.util.DelayedTask(this.showMenu, this);
        this.hideTask = new Ext.util.DelayedTask(function() {
            this.showTask.cancel();
            this.hideAll();
            this.fireEvent('hide');
        }, this);

        this.el.hover(function() {
            this.hideTask.cancel();
        }, function() {
            this.hideTask.delay(this.delay*1000);
        }, this);

        // for each item that has a submenu, create a mouseenter function that shows its submenu
        // delay 5 to make sure enter is fired after mouseover
        this.el.select('li.ux-menu-item-parent').on('mouseenter', this.onParentEnter, false, {me: this, delay: 5});

        // listen for mouseover events on items to hide other items submenus and remove hovers
        this.el.on('mouseover', function(ev, t) {
            this.manageSiblings(t);
            // if this item does not have a submenu, the showMenu task for a sibling could potentially still be fired, so cancel it
            if(!Ext.fly(t).hasClass('ux-menu-item-parent')) {
                this.showTask.cancel();
            }
        }, this, {delegate: 'li'});

        this.el.on('click', function(ev, t) {
            return this.fireEvent('click', ev, t, this);
        }, this, {delegate: 'a'})
    },

    onParentEnter: function(ev, link, o) {
        var item = Ext.get(this),
            me = o.me;

        // if this item is in a submenu and contains a submenu, check if the submenu is not still animating
        if(!item.hasClass('ux-menu-item-main') && item.parent('ul').hasActiveFx()) {
            item.parent('ul').stopFx(true);
        }

        // if submenu is already shown dont do anything
        if(!item.child('ul').hasClass('ux-menu-hidden')) {
            return;
        }
        
        me.showTask.delay(me.delay*1000, false, false, [item]);   
    },

    showMenu : function(item) {
        var menu = item.child('ul'),
            x = y = 0;

        item.select('>a').addClass('ux-menu-link-hover');

        // some different configurations require different positioning
        if(this.direction == 'horizontal' && item.hasClass('ux-menu-item-main')) {
            y = item.getHeight();
        }
        else {
            x = item.getWidth();
        }

        // if its ie, force a repaint of the submenu
        if(Ext.isIE) {
            menu.select('ul').addClass('ux-menu-hidden');
            // ie bugs...
            if(Ext.isBorderBox || Ext.isIE7) {
                item.down('iframe').setStyle({left: x + 'px', top: y + 'px', display: 'block'});
            }
        }

        menu.setStyle({left: x + 'px', top: y + 'px'}).removeClass('ux-menu-hidden');

        if(this.animate) {
            switch(this.transitionType) {
                case 'slide':
                    if(this.direction == 'horizontal' && item.hasClass('ux-menu-item-main')) {
                        menu.slideIn('t', {
                            duration: this.transitionDuration
                        });
                    }
                    else {
                        var smBot = menu.getHeight()+menu.getTop();
                        var vmHeight = Math.floor(smBot+50), viewHeight = Ext.lib.Dom.getViewHeight();
                        if (vmHeight > viewHeight){
                            var mmBot = item.getHeight()+item.getTop();
                            var offSet = (vmHeight-viewHeight);
                            if ((smBot-offSet) < mmBot) {
                                offSet = (mmBot-smBot)*-1;
                            }
                            menu.setStyle('top','-'+offSet+'px');
                        }
                        menu.slideIn('l', {
                            duration: this.transitionDuration
                        });
                    }
                break;

                default:
                    menu.setOpacity(0.001).fadeIn({
                        duration: this.transitionDuration
                    });
                break
            }
        }
        
        this.fireEvent('show', item, menu, this);
    },

    manageSiblings: function(item) {
        var item = Ext.get(item);
        item.parent().select('li.ux-menu-item-parent').each(function(child) {
            if(child.dom.id !== item.dom.id) {
                child.select('>a').removeClass('ux-menu-link-hover');
                child.select('ul').stopFx(false).addClass('ux-menu-hidden');
                if (Ext.isBorderBox || Ext.isIE7) {
                    child.select('iframe').setStyle('display', 'none');
                }
            }
        });
    },

    hideAll: function() {
        this.manageSiblings(this.el);
    },
    
    setCurrent: function() {
        var els = this.el.query('.' + this.currentClass);
        if(!els.length) {
            return;
        }
        var item = Ext.get(els[els.length-1]).removeClass(this.currentClass).findParent('li', null, true);
        while(item && item.parent('.ux-menu')) {
            item.down('a').addClass(this.currentClass);
            item = item.parent('li');
        }
    },

    doAutoWidth: function() {
        var fixWidth = function(sub) {
            var widest = 0, hasSplit = 1;
            var items = sub.select('>li');
            if (!sub.up('ul').hasClass('ux-menu')){
                if (items.elements.length > 17) {
                    var splitLength = Math.ceil(items.elements.length/2);
                    sub.select('>li:nth('+splitLength+')').addClass('ux-menu-split');
                    hasSplit = sub.select('>li.ux-menu-split').elements.length + 1;
                }
            }

            sub.setStyle({width: 3000 + 'px'});
            items.each(function(item) {
                widest = Math.max(widest, item.getWidth());
            });

            widest = Ext.isIE ? widest + 1 : widest;
            items.setWidth((widest + 24) + 'px');
            sub.setWidth(((widest + 25)*hasSplit) + 'px');
        }

        if(this.direction == 'vertical') {
            this.container.select('ul').each(fixWidth);
        }
        else {
            this.el.select('ul').each(fixWidth);
        }
        
    }
});

Ext.ux.Menu.zSeed = 50;

Ext.onReady(function(){
    new Ext.ux.Menu('hstopmenu', {
        transitionType: 'slide',
        delay: 0.2, 
        transitionDuration: 0.2
    });
    if (readCookie('chatPop') !== 'close' && Ext.fly('clicktochat')) {
		var checkImage = function() {
	        if(Ext.get('clicktochat').child('img').dom.complete){
				if (Ext.get('clicktochat').child('img').getWidth() == 144) {
					Ext.ux.SimplePop.init();
					Ext.ux.SimplePop.open('clicktochat');
				}
	            Ext.TaskMgr.stop(ldd);
	        }
	    };
		var ldd = Ext.TaskMgr.start({
            run: checkImage, 
            interval: 100,
			repeat: 30
        });
        Ext.get('kampylink').setStyle('z-index', '14000');
    }
    
    Ext.get('didYouKnowClose').on('click', function(e) {
	    e.preventDefault();
	    e.stopPropagation();
	    hideDidYouKnow();
	});
	showDidYouKnow();
});