/*
 * Ext JS Library 2.2
 * Copyright(c) 2006-2008, Ext JS, LLC.
 * licensing@extjs.com
 * 
 * http://extjs.com/license
 */

Ext.onReady(function(){
Ext.QuickTips.init();
	var shout_win;	// Carries the Shoutbox Window
	var vent_win;	// Carries the Ventrilo Window
	var forum_win;	// Carries the Ventrilo Window
	var css_win;
	var cssip;
	var cssport;
	var ip; 
	var port;
	var vent_name;
	var password;
	
    var shoutButton = Ext.get('show-btn');	// Attach to HTML Button
	var ventButton 	= Ext.get('show-vent');	// Attach to HTML Button
	var cssButton 	= Ext.get('show-css');	// Attach to HTML Button
	var forumButton 	= Ext.get('show-forum');	// Attach to HTML Button
	

	// ON Button Click
    shoutButton.on('click', function(){
        // create the window on the first click and reuse on subsequent clicks
        if(!shout_win){
            shout_win = new Ext.Window({
                applyTo     : 'hello-win',
				id			: 'hello-win',
                layout      : 'fit',
                width       : 450,
				x: 10,
				y: 50,
                height      : 250,
				maximizable: true,
				collapsible :true,
				closeAction :'hide',
                plain       : true,
				toolTip: {text:'Open Shoutbox'},
				buttonAlign: 'center',
                buttons: [{
					class : 'wide-button',
                    text     : 'Shout',
                    handler	 : function(){
						add(); return false;
					}
                }]
            });
        }
		// window already exsist
        shout_win.show(shoutButton);
		shout_win.body.mask('Loading', 'x-mask-loading');
		//refresh();
		// After Loading window, scroll to very bottom
		setTimeout("scroll_wall(9999)",500);
    });
 
	
	
	// Start Forum thing.
	   var ds = new Ext.data.Store({
        proxy: new Ext.data.ScriptTagProxy({
            url: 'http://hallofthegods.com/phpbb3/forum-remote.php'
        }),
        reader: new Ext.data.JsonReader({
            root: 'topics',
            totalProperty: 'totalCount',
            id: 'post_id'
        }, [
            {name: 'postId', mapping: 'post_id'},
            {name: 'title', mapping: 'topic_title'},
            {name: 'subject', mapping: 'post_subject'},			
            {name: 'topicId', mapping: 'topic_id'},
            {name: 'author', mapping: 'author'},
            {name: 'lastPost', mapping: 'post_time', type: 'date', dateFormat: 'timestamp'},
            {name: 'excerpt', mapping: 'post_text'}
        ]),

        baseParams: {limit:5, forumId: 4}
    });

    // Custom rendering Template for the View
    var resultTpl = new Ext.XTemplate(
        '<tpl for=".">',
        '<div class="search-item">',
            '<filedset><legend><h3><a href="#" onclick="load_website(\'forum.hallofthegods.com/viewtopic.php?t={topicId}&p={postId}#p{postId}\')">{title}</a><br><span>{lastPost:date("M j, Y")} by {author}</span></h3></legend>',
            '<p>{excerpt}</p>',
			'</fieldset>',
        '</div></tpl>'
    );

	function get_vent_info(){
		 ip = (!ip)?ventframe.document.getElementById('ip').value:ip;
		 port = (!port)?ventframe.document.getElementById('port').value:port;
		 vent_name = (!vent_name)?ventframe.document.getElementById('server_name').value:vent_name;
		 password = (!password)?ventframe.document.getElementById('password').value:password;
	}
	
	forumButton.on('click',function(){
		if(!forum_win){
			forum_win = new Ext.Window({
                applyTo     : 'search-panel',
				id			: 'search-panel',
				title:	'[HoG] Forum Search',
				y: 50,
				x: (window.document.body.clientWidth - 450),
                layout      : 'fit',
                width       : 375,
                height      : 450,				
				maximizable:  false,
				collapsible :true,
				closeAction :'hide',
                plain       : true,
				buttonAlign: 'center',
				items: new Ext.Panel({
					
					autoScroll:true,
			
					items: new Ext.DataView({
						tpl: resultTpl,
						store: ds,
						itemSelector: 'div.search-item'
					}),
			
					bbar: [
						new Ext.app.SearchField({
							store: ds,
							width:350
						})
					],
			
					tbar: new Ext.PagingToolbar({
						store: ds,
						pageSize: 20,
						displayInfo: true,
						displayMsg: 'Topics {0} - {1} of {2}',
						collapsible: true,
						emptyMsg: "No topics to display"
					})
				})
			});
			ds.load({params:{start:0, limit:5, forumId: 4}});
		}
		forum_win.show(forumButton);
		
	});
	
	
	var tools = [{
	id:'gear',
	handler: function(){
		document.getElementById('ventframe').src = 'http://www.hallofthegods.com/vent/ventrilo.php?ip=67.19.104.10&port=3845';
		Ext.Msg.alert('Message', 'Vent Window Refreshed.');
		}
	}];

	
	ventButton.on('click', function(){
        // create the window on the first click and reuse on subsequent clicks
        if(!vent_win){
            vent_win = new Ext.Window({
                applyTo     : 'vent-win',
				id			: 'vent-win',
                layout      : 'fit',
                width       : 350,
                height      : 500,
				y: 50,
				tools:[{
                            id:'refresh',
                            on:{
                                click: function(){
                                    var tree = Ext.getCmp('vent-win');
                                    document.getElementById('ventframe').src = 'http://www.hallofthegods.com/vent/ventrilo.php?ip=67.19.104.10&port=3845';
									tree.body.mask('Loading', 'x-mask-loading');
                                    //tree.root.reload();
                                    //tree.body.collapse(true, false);
                                    setTimeout(function(){ // mimic a server call
                                        tree.body.unmask();
                                        //tree.body.expand(true, true);
                                    }, 1000);
                                }
                            }
                        }],
				//root: autoload{url: 'http://www.hallofthegods.com/vent/ventrilo.php?ip=vent.hallofgods.com&port=3845'}
				maximizable: false,
				collapsible :true,
				closeAction :'hide',
                plain       : true,
				buttonAlign: 'center',
				buttons: [{
                    text     : 'Launch Ventrilo & Join Server',
                    handler	 : function(){
						get_vent_info();
					 window.location.href = 'ventrilo://'+ip+':'+port+'/servername='+vent_name+'&serverpassword='+password;
					}
                }]
            });
        }
        vent_win.show(ventButton);

		
    });
	
	function get_css_info(){
		 cssip = (!cssip)?mapframe.document.getElementById('ip').value:cssip;
		 cssport = (!cssport)?mapframe.document.getElementById('port').value:cssport;
 
	}
	
	function resizeStats(){
		resize_me = Ext.getCmp('css-win');
		resize_me.setSize(800,500);
	}

	cssButton.on('click', function(){
        // create the window on the first click and reuse on subsequent clicks
        
 		
		if(!css_win){
            css_win = new Ext.Window({
				applyTo     : 'css-win',
				id			: 'css-win',
				layout		: 'fit',
				autoScroll	: false,
                width       : 325,
                height      : 275,
				autoSize: 	true,
				
				y: 300,
				bufferResize	: true,
				items		: new Ext.TabPanel({
					activeItem	: 0,
					items		: [
						{
							html : '<iframe width="99%" id="mapframe" name="mapframe" style="  overflow: hidden" height="100%"  src="http://stats.hallofthegods.com/pingserver/?big=1" style=" border: 0; overflow: auto;"></iframe>',
							title	: 'Now Playing',
							listeners: {activate: function (){
								css_win = Ext.getCmp('css-win');
								css_win.setSize(300,275);
								css_win.center()
								}
							}
							
						},
						{
							html : '<iframe width="99%" id="mapframe" name="mapframe" style=" overflow: auto" height="100%"  src="http://stats.hallofthegods.com" style=" border: 0; overflow: auto;"></iframe>',
							title	: 'Live Stats',
							listeners: {activate: function(){
								css_win = Ext.getCmp('css-win');
								css_win.setSize(805,500);
								css_win.center()
								}
							}
						}
					],
				}),
				tools:[{
                            id:'refresh',
                            on:{
                                click: function(){
                                    var tree = Ext.getCmp('css-win');
                                    document.getElementById('mapframe').src = 'http://stats.hallofthegods.com/pingserver/?big=1';
									tree.body.mask('Loading', 'x-mask-loading');
                                    //tree.root.reload();
                                    //tree.body.collapse(true, false);
                                    setTimeout(function(){ // mimic a server call
                                        tree.body.unmask();
                                        //tree.body.expand(true, true);
                                    }, 1000);
                                }
                            }
                        }],
				//root: autoload{url: 'http://www.hallofthegods.com/vent/ventrilo.php?ip=vent.hallofgods.com&port=3845'}
				maximizable: false,
				collapsible :true,
				closeAction :'hide',
				maxWidth	: 800,
                plain       : true,
				buttonAlign: 'center',
				buttons: [{
                    text     : 'Click to Play NOW!',
                    handler	 : function(){
						//get_css_info();
						//steam:%20"-applaunch%20240%20-game%20cstrike%20+connect%20css.hallofgods.com:27015"
					 window.location.href = 'steam://connect/css.hallofgods.com:27015';
					}
                }]
            });
        }
        css_win.show(cssButton);
		
    });
});
	
	var check_n = 0;
	 
	var old_data = "--";
	var update_flag = false;
	function refresh_cb(new_data) {	
		if (new_data != old_data) {
			document.getElementById("wall").innerHTML = new_data;
			scroll_wall(5000);
			old_data = new_data;
		}	
		  
		  var currentTime = new Date()
		  var hours = currentTime.getHours()
		  var minutes = currentTime.getMinutes()
		  var seconds = currentTime.getSeconds();
		  var suffix = "AM";
		  
		  if (hours >= 12) {
		  suffix = "PM";
		  hours = hours - 12;
		  }
		  if (hours == 0) {
		  hours = 12;
		  }
		
		  if (minutes < 10)
		  minutes = "0" + minutes
		  
		   if (seconds < 10)
		  seconds = "0" + seconds

		
		document.getElementById("status").innerHTML = "Checked @ "+hours+":"+minutes+":"+seconds+suffix;
		
		if(update_flag){
			update_flag = false;
		} else {
			sajax_request_type = "GET";
			setTimeout("refresh()", 5000);
		}

	}
	
	function update_handle_cb(handle){
		document.getElementById('handle').value = handle;
	}
	var shoutframe = false;
	function refresh() {
		document.getElementById("status").innerHTML = "Checking... "+" #" + check_n++;
		
		
		shout_flag = Ext.getCmp('hello-win');
		

		if(shout_flag){
			flag = shout_flag.hidden;
			shout_flag.body.unmask();
			if(!flag){			
				x_refresh(refresh_cb);
				handle = document.getElementById('handle').value;
				if(handle == 'guest' || handle == 'anonyomous' ){
					x_update_handle(update_handle_cb);	
				}
			} else {
				setTimeout("refresh()", 1000);
			}
		} else {
			setTimeout("refresh()", 1000);
		}
	}
	
	
	function scroll_wall(yAxis){
		document.getElementById('x-window-body').scrollTop = yAxis;
		document.getElementById('x-window-body').scrollBottom = -yAxis;
	}
	function submitenter(myfield,e){
		var keycode;
		if (window.event) keycode = window.event.keyCode;
		else if (e) keycode = e.which;
		else return true;
		if (keycode == 13)
		{
		add();
		return false;
		}
		else
		return true;
	}
	// use for address bar
	function submitaddress(myfield,e){
		var keycode;
		if (window.event) keycode = window.event.keyCode;
		else if (e) keycode = e.which;
		else return true;
		if (keycode == 13)
		{
			if(document.getElementById('go').checked){
				load_website(myfield.value);	
			}else{
				search_website(myfield.value);
			}
		
		return false;
		}
		else
		return true;
	}
	function add_cb(handle) {
		// we don't care..
		// yes we do
		document.getElementById('handle').value = handle;
		if(update_flag){
			return;
		} else {
			update_flag = true;
			refresh();
		}
	}

	function add() {
		var line;
		var handle;
		handle = document.getElementById("handle").value;
		line = document.getElementById("line").value;
		if (line == "") 
			return;
		sajax_request_type = "POST";
		x_add_line(  handle , line, add_cb);
		document.getElementById("line").value = "";
	}
