var Menu = function(type){
    this.menu = null
    this.offsetTop = 0
    this.offsetLeft = 0
    this.visible = 0
    this.localColumnN = 0
    this.permutationBlocks = {}
    this.permutationCaptions = {}
    this.userSet = null
    this.userMenu = null
    this.type = type
    this.view = null

    this.init = function(){
        this.menu = (this.type == TVProgram.CHANNELS) ? $('channelMenu') : $('genreMenu')
        for (var node = TVProgram.tvCaptionsContainer; node && node.nodeType == 1 && node.getAttribute('id') != "rootTVProgram"; node = node.parentNode){
            //this.offsetTop += node.offsetTop
           // this.offsetLeft += node.offsetLeft
        }
        this.offsetTop += TVProgram.tvCaptionsContainer.offsetHeight
        this.menu.onmousedown = stopPropagation
    }

    this.toggle = function(o){
        if (this.visible == 2) {
            this.visible = 0
            return
        }
	
	if (this.caption) this.caption.getElementsByTagName('a')[0].onmousedown = null
	
        //this.caption = o
        for (var li=o; li.className.indexOf('channel_caption')==-1; li=li.parentNode);
        this.caption = li
        //this.caption.className = 'channel_hover'
		//$('tvCaptions').style.position = "relative";
		this.caption.className += ' active'
        this.menu.style.display = 'block'
        this.menu.style.top = (this.offsetTop + 37) + 'px'

        this.localColumnN = Math.round((this.caption.offsetLeft - TVProgram.tvCaptionsContainer.scrollLeft) / TVProgram.blockWidth);
        //var dir = (this.localColumnN > 2) ? 1 : -1;
        //this.menu.style.left = this.offsetLeft + this.caption.offsetLeft - TVProgram.tvCaptionsContainer.scrollLeft - (dir + 1)*TVProgram.blockWidth - dir*5 + 'px'
        if (this.localColumnN > 2){
            this.menu.style.left = this.offsetLeft + this.caption.offsetLeft - TVProgram.tvCaptionsContainer.scrollLeft + TVProgram.blockWidth -this.menu.offsetWidth + 5 + 'px'
        } else {
            this.menu.style.left = this.offsetLeft + this.caption.offsetLeft - TVProgram.tvCaptionsContainer.scrollLeft + 8 + 'px'
        }
        this.visible = 1
        var menu = this
        if (TVProgram.tvProgramContainer.className.indexOf(' fade') == -1) {
           TVProgram.tvProgramContainer.className = TVProgram.tvProgramContainer.className.replace('tvProgramContainer', 'tvProgramContainer fade')
        }
	
        document.onmousedown = function(){
            menu.hide()
            menu.visible = 0
	    document.onmousedown = null
        }
	
	var a = this.caption.getElementsByTagName('a')[0]
        a.onmousedown = function(e){
            menu.hide()
            menu.visible = 2
            stopPropagation(e)
	    a.onmousedown = null
        }
        
    }

    this.expand = function(o){
        if (o == this.caption) return
        if (this.caption) this.caption.className = this.caption.className.replace(' active', '')
        //o.className += ' active'
        
        //if (this.caption) this.caption.className = 'channel_caption'
        if (this.visible==1) this.toggle(o)
    }

    this.hide = function(){
        //this.caption.className = 'channel_caption'
        this.menu.style.display = 'none'
        document.onmousedown = null
        if (this.caption) this.caption.className = this.caption.className.replace(' active', '')
        //this.caption.className = this.caption.className.replace(' active', '')        
        this.visible = 0
        this.caption.getElementsByTagName('a')[0].onmousedown = null
        TVProgram.tvProgramContainer.className = TVProgram.tvProgramContainer.className.replace(' fade', '')
        /*
        var a = this.caption.getElementsByTagName('a')[0]
        a.onmousedown = this.stopPropagation
        setTimeout(function(){
            a.onmousedown = null
        }, 0)
        */
        
    }

    this.createUserSet = function(columnN){
    	TVProgram.scroll.menuPos = TVProgram.scroll.scrollHeight
    	$('bottomMenus1').scrollTop = 0
        if (this.view.columnSetN == this.view.allSetN) {
            this.view.columnSets[this.view.userSetIndex] = []
            for (var i=0; i<TVProgram.view.width; i++){
                this.view.columnSets[this.view.userSetIndex][i] = i
            }
        }
        else this.view.columnSets[this.view.userSetIndex] = this.view.columnSets[this.view.columnSetN].slice()
        this.userSet = this.view.columnSets[this.view.userSetIndex]

        if (this.type == TVProgram.CHANNELS) {
            this.userMenu = BottomMenu.bottomMenus[this.view.columnSetN].cloneNode(true)
            $('bottomMenus1').appendChild(this.userMenu)
            BottomMenu.bottomMenus[this.view.userSetIndex] = this.userMenu
            with ($('channelSets')) {
                options[this.view.userSetIndex].style.display = 'block'
                selectedIndex = this.view.userSetIndex
                
                //selectMenu.addItem('channelSets', 'channelSets2');
            }
            /*var ls = $('channelSets2').getElementsByTagName("li");
            if (ls.length >= 2) {
            	ls[ls.length - 1].className = "last";
            	ls[ls.length - 1].style.display = "block";
            	ls[ls.length - 2].className = "itm";
            }
			selectMenu.onItemClick('channelSets', this.view.userSetIndex, 'Мои каналы');*/
			this.addChannelSetMenuItem('Мои каналы');
        }
    }

    this.cloneBlock = function(x, tvProgramN, columnN, localColumnN, index){
        var tvProgram = TVProgram.tvPrograms[tvProgramN]
        var block, caption
        if (index != -1) {
            block = tvProgram.childNodes[index].cloneNode(true)
        }
		else
		if ((block = TVProgram.view.blocks[(TVProgram.y + tvProgramN - 1) + '' + columnN]) && (block = block['html'])) block = block.cloneNode(true);
        else {
            block = $('protoBlock').cloneNode(true);
            block.removeAttribute('id')
            block.style.display = 'block'
        }
	
        tvProgram.removeChild(tvProgram.childNodes[x])
        if (x < tvProgram.childNodes.length) tvProgram.insertBefore(block, tvProgram.childNodes[x])
        else tvProgram.appendChild(block)
        Mediator.notify(View.CONTENT_CHANGED)

        if (!this.permutationBlocks[columnN][localColumnN]) this.permutationBlocks[columnN][localColumnN] = {}
        this.permutationBlocks[columnN][localColumnN][TVProgram.y + tvProgramN - 1] = block
    }

    this.cloneCaption = function(x, tvProgramN, columnN, localColumnN, index){
        var caption
        if (index != -1) caption = TVProgram.tvCaptions.childNodes[index].cloneNode(true)
	else
	if (caption = TVProgram.view.captions[columnN]) caption = caption.cloneNode(true);
        else {
            caption = $('protoCaption').cloneNode(true);
            caption.removeAttribute('id')
            caption.style.display = 'block'
        }
	
//	if (TVProgram.view.captions[columnN]) alert(columnN +','+ TVProgram.view.captions[columnN].innerHTML)
//alert(caption)
        TVProgram.tvCaptions.removeChild(TVProgram.tvCaptions.childNodes[x])
        if (x < TVProgram.tvCaptions.childNodes.length) TVProgram.tvCaptions.insertBefore(caption, TVProgram.tvCaptions.childNodes[x])
        else TVProgram.tvCaptions.appendChild(caption)

        this.permutationCaptions[columnN][localColumnN] = caption
    }

    this.changeColumn = function(columnN){
        this.hide()
        var localColumnN = TVProgram.view.x + this.localColumnN // prev & next
        var globalColumnN = (this.view.columnSetN == this.view.allSetN) ? localColumnN : this.view.columnSets[this.view.columnSetN][this.view.x + this.localColumnN] //prev
        if (globalColumnN == columnN) return

        if (this.type == TVProgram.CHANNELS) {
            if (this.view.columnSetN != this.view.userSetIndex) {
                if (this.userMenu) {
                    this.userMenu.parentNode.removeChild(this.userMenu)
                    this.userMenu = null
                }
                this.createUserSet(columnN)
                this.permutationBlocks = {}
                this.view.columnSetN = this.view.userSetIndex
            }
        } else {
            if (!this.userSet) this.createUserSet(columnN)
            this.view.columnSetN = this.view.userSetIndex
        }

        this.userSet[this.view.x + this.localColumnN] = columnN

        var block
        if (this.permutationBlocks[globalColumnN]) {
            delete this.permutationBlocks[globalColumnN][localColumnN]
            delete this.permutationCaptions[globalColumnN][localColumnN]
        }
        if (!this.permutationBlocks[columnN]) {
            this.permutationBlocks[columnN] = {}
            this.permutationCaptions[columnN] = {}
        }
        
        var x = TVProgram.tvProgramContainer.scrollLeft / TVProgram.blockWidth + this.localColumnN
        for (var i = this.view.x - TVProgram.groupLength, j = 0, ilen = this.view.x + 2 * TVProgram.groupLength; i < ilen && i<this.view.width; i++) {
            if (i < 0) continue
            if (this.userSet[i] == columnN && i != localColumnN) {
                if (TVProgram.y > TVProgram.minY) this.cloneBlock(x, 0, columnN, localColumnN, j)

                this.cloneBlock(x, 1, columnN, localColumnN, j)
                this.cloneCaption(x, 1, columnN, localColumnN, j)

                if (TVProgram.y < TVProgram.height - 1) this.cloneBlock(x, 2, columnN, localColumnN, j)

                if (this.type == TVProgram.CHANNELS) this.userMenu.getElementsByTagName('td')[localColumnN].innerHTML = Settings.channelNames[columnN]

                return
            }
            j++
        }

        if (TVProgram.y > TVProgram.minY) {
            this.cloneBlock(x, 0, columnN, localColumnN, -1)
            this.view.getBlock(TVProgram.y - 1, localColumnN)
		}
		
		this.cloneBlock(x, 1, columnN, localColumnN, -1)
        this.cloneCaption(x, 1, columnN, localColumnN, -1)
        this.view.getBlock(TVProgram.y, localColumnN)
        this.view.getCaption(localColumnN)
        if (TVProgram.y < TVProgram.height - 1) {
	    	this.cloneBlock(x, 2, columnN, localColumnN, -1)
	    	this.view.getBlock(TVProgram.y + 1, localColumnN)
		}
        if (this.type == TVProgram.CHANNELS) this.userMenu.getElementsByTagName('td')[localColumnN].innerHTML = Settings.channelNames[columnN]
    }
    
	this.addChannelSetMenuItem = function(txt) {
		var el = js.createElement("li", {_class: "itm last", id: "item3_" + this.view.userSetIndex}, txt);
		js.last('li', js.$('dropdown3_items')).className = "itm";
		
		js.addEvent("onmouseout", function() {
			js.toggleClass(this, 'hover', 'itm');
		}, el);
		
		js.addEvent("onmouseover", function() {
			js.toggleClass(this, 'hover', 'itm');
		}, el);	
		
		js.addEvent("onclick", function() {
			var index = this.id.split("_").pop();
			js.$('dropdown3_text').firstChild.innerHTML = this.innerHTML;
			js.$('channelSets').selectedIndex = index;
			js.$('channelSets').onchange();
		}, el);	
		
		
		js.$('dropdown3_text').firstChild.innerHTML = txt;
		js.appendObj(js.$('dropdown3_items'), el);
	}
}



var channelMenu = new Menu(TVProgram.CHANNELS)
var genreMenu = new Menu(TVProgram.GENRES)

var BottomMenu = {

	MENU_SHOW : 'menu_show',
	MENU_HIDE : 'menu_hide',

    top : 0,
    left : 0,
    bottomMenus : {},
    visible : 0,
    delay : 0,

    initBottomMenus : function() {
        var tables = $('bottomMenus').getElementsByTagName('table')
        //this.top = TVProgram.tvProgramContainer.offsetHeight
        //this.left = TVProgram.tvProgramContainer.offsetWidth
        //this.top = this.top - 80
        //this.left = this.left - 338
        /*widthStat = ""
        for (var parent = TVProgram.tvProgramContainer; parent && parent.nodeType == 1; parent = parent.parentNode) {
            if ((parent.tagName != "TABLE") && (parent.tagName != "TR") && (parent.tagName != "TBODY") && (parent.tagName != "HTML") && (parent.tagName != "BODY")) {
            	this.top += parent.offsetTop
            	this.left += parent.offsetLeft
            	widthStat += parent.tagName + " / " + parent.className + " / " + parent.offsetLeft + " / " + this.left + "\n"
            }
        }
        alert(widthStat)*/
        for (var i = 0,ilen = tables.length; i < ilen; i++) {
            this.bottomMenus[i] = tables[i]
            tables[i].onmouseover=null
            tables[i].onmouseout=null
           	tables[i].style.display = 'none'
        }

        $('bottomMenus').style.MozUserSelect = 'none'
        this.delay = Settings.bottomMenuHideDelayMs
        this.bacCGP = this.changeChannelGroup
    },

    changeChannelGroup : function(x){
        this.hide()
        TVProgram.view.oldX = TVProgram.view.x
        if (TVProgram.view.x == x) return
        TVProgram.moveTo(x, TVProgram.y)
        Mediator.notify(Mediator.END_MOVE_SETKA, this)
        TVProgram.setupButtons()
		Mediator.notify(View.CONTENT_CHANGED, this)
    },
    
    toggleHide : function(){
    	if (this.visible) this.visible = 2
    },

    show : function(){
        //this.stopHide()
        
        if (this.visible) {
        	if (this.visible==2) this.visible = 0
        	return
        }
        var menu = this.bottomMenus[TVProgram.view.columnSetN]
        var menuParrnt =  $('bottomMenus')
        if ($('bottomChannelsGroupButton').className.indexOf('_disabled') > -1) return
        TVProgram.tvProgramContainer.className = TVProgram.tvProgramContainer.className.replace('tvProgramContainer', 'tvProgramContainer fade')
        this.visible = 1
        menu.style.display = ''
        menuParrnt.style.display = 'block'
      
        menuParrnt.style.top = 85 + 'px'
        menuParrnt.style.left = -341 + 'px'
        
        document.onmousedown = function(e){setTimeout(function(){
	        BottomMenu.hide(menu)
        }, 0)}
        
        Mediator.notify(BottomMenu.MENU_SHOW, this)
        // Загорается кнопка "Выбор каналов" (изменил Флерко)
        js.addClass($('select_channel_btn'),'active')
    },

    hide : function(menu){
    	document.onmousedown = null
    	if (this.visible != 2) this.visible = 0
        menu = menu || this.bottomMenus[TVProgram.view.columnSetN]
        menu.style.display = 'none'
        $('bottomMenus').style.display = 'none'
        TVProgram.tvProgramContainer.className = TVProgram.tvProgramContainer.className.replace(' fade', '')
        
        //this.stopHide()
        Mediator.notify(BottomMenu.MENU_HIDE, this)
        this.changeChannelGroup = this.bacCGP
        // Гаснет кнопка "Выбор каналов" (изменил Флерко)
        $('select_channel_btn').className=""
    }

	/*
    startHide : function(menu){
        menu = menu || this.bottomMenus[TVProgram.view.columnSetN]
        var bottomMenu = this
        this.hideTimeout = setTimeout(function(){
            bottomMenu.hide(menu)
        }, this.delay)
    },

    stopHide : function(){
        if (this.hideTimeout) clearTimeout(this.hideTimeout)
        this.hideTimeout = null
    }
	*/
}

var Anons = {
    delay : 500,
    timeouts : {},
    anonsProto : null,
    anons : null,
    channelN : -1,
    dayN : -1,
    teleCastN : -1,
    visible : 0,
    tvProgramContainerLeft :0,

    init : function(){
    	this.addListener = Mediator.addListener
        this.anonsProto = $('anonsProto')
        this.anons = $('anons')
        this.delay = Settings.anonsDelayMs


        for (var node = TVProgram.tvProgramContainer; node && node.nodeType==1; node = node.parentNode){
            this.tvProgramContainerLeft += node.offsetLeft
        }

        var AnonsLoadedListener = {
            exec : function(eventSource, params, request){
                if (Anons.channelN == params.columnN && TVProgram.weekN == params.weekN && Anons.dayN == params.dayN && Anons.teleCastN == params.teleCastN) {
                
                    //Anons.anons.style.visibility = 'hidden'
                    Anons.anons.style.display = 'block'
                    //var height = Anons.anons.offsetHeight
                    
                    var anonsEl = request.responseXML.documentElement.getElementsByTagName('div')[0]
                    Anons.anons.className = anonsEl.getAttribute('class')
                    Anons.anons.innerHTML = Loader.serialize(anonsEl)
                    
                    //$('print').value += Anons.anons.offsetTop

					//Anons.anons.parentNode.removeChild(Anons.anons)
        			//$("tv_").appendChild(Anons.anons)
        						
					
                    //var content = $('anonsContent')
                    //var contentHeight = content.offsetHeight
                    //content.style.height = 'auto'

                    //if (content.offsetHeight < contentHeight) content.style.height = contentHeight + 'px'
                    //Anons.anons.style.top = Anons.anons.offsetTop + height - Anons.anons.offsetHeight + 'px'
                    
                    /*
                    var localColumnN = (Anons.telecast.parentNode.offsetLeft - TVProgram.tvCaptionsContainer.scrollLeft) / TVProgram.blockWidth
		            var ColPos = (Math.ceil(localColumnN + 1) - 1) * 150            
		            if (localColumnN > 2) {
		                Anons.anons.className = Anons.anons.className + ' right'
		                //left = Anons.telecast.offsetLeft + Anons.telecast.offsetWidth - Anons.anons.offsetWidth - TVProgram.tvProgramContainer.scrollLeft
		                left = ColPos + 150 - Anons.anons.offsetWidth		               
		            } else {
		            	Anons.anons.className = Anons.anons.className.replace(' right', '')		               
		                left = ColPos                           
		            }
                    */
                    
                    /* raschet koordinat WORK LAST*/
                    //Anons.anons.style.top = (Anons.telecast.offsetTop - Anons.anons.offsetHeight - TVProgram.tvPrograms[1].scrollTop + 29 + 35 + 10) + 'px'
                    //Anons.anons.style.left = left + 'px'
                    /* END raschet koordinat WORK LAST*/
                    //Anons.anons.style.top = "0"
                    //Anons.anons.style.left = "0"
                    
                    //Anons.anons.style.display = 'block'
                    Anons.anons.style.visibility = 'visible'
                    TVProgram.tvProgramContainer.className = TVProgram.tvProgramContainer.className.replace('tvProgramContainer', 'tvProgramContainer fade')
                    document.onmousedown = function(){
		                Anons.hide()
		                document.onmousedown = null
		            }
                }
            }
        }
        this.addListener(Mediator.LOAD_ANONS, AnonsLoadedListener)
    },

    startShow : function(event, telecast, channelN, dayN, teleCastN){
    
        if (this.visible == 2) return;
        this.key = '' + channelN + dayN + teleCastN
        //this.timeouts['' + channelN + dayN + teleCastN] = setTimeout(function(){
        
        	
        	
            Anons.channelN = channelN
            Anons.dayN = dayN
            Anons.teleCastN = teleCastN
            Anons.telecast = telecast
            Anons.visible = 1
            Loader.load(Mediator.LOAD_ANONS,
                        Anons,
                        {columnN : channelN, weekN : TVProgram.weekN, dayN : dayN, teleCastN : teleCastN},
                        {id : Settings.channelSets[Settings.allSetN][channelN], week : TVProgram.weekN, day : dayN, telecast : teleCastN})
        //}, this.delay)
            
            //Anons.anons.style.height = ''
            
    },

    stopShow : function(channelN, dayN, teleCastN){
        //if (this.timeouts['' + channelN + dayN + teleCastN]) clearTimeout(this.timeouts['' + channelN + dayN + teleCastN])
    },

    hide : function(channelN, dayN, teleCastN){
        //if (this.channelN == channelN && this.dayN == dayN && this.teleCastN == teleCastN) {
        if (this.visible == 0 || this.visible == 2) return;
	
        
        //Anons.anons.parentNode.removeChild(Anons.anons)
        //document.documentElement.appendChild(Anons.anons)
        
        this.anons.style.display = 'none'
        TVProgram.tvProgramContainer.className = TVProgram.tvProgramContainer.className.replace(' fade', '')
        this.anons.style.top = 0
        this.channelN = -1
        this.dayN = -1
        this.teleCastN = -1
        this.visible = 0
        
    },
    
    toString : function(){ return 'anons'}
}
