var originalNews = 6;
var originalPosts = 6;
var oldNews = originalNews;
var oldPosts = originalPosts;
var isSet = false;
var increment = 0;
var stopCheck;
var finalCheck = false;
var oCurrentHeight = 0;
var originalIFrame = 0;
var additionalOffset = 0;
var checkedYet = false;
var done = true;
var ready = false;
var avatarTimestamp = new Date().getTime();
var soundToPlay = "";
var soundsToLoad = {};
var smReady = false;
var enteredChatNow = false;
var skin = "";
var apngNeeded;

function enteredChat() {
	enteredChatNow = true;
}

String.prototype.reverse = function () {
    return this.split('').reverse().join('');
};

String.prototype.replaceLast = function (what, replacement) {
    return this.reverse().replace(new RegExp(what.reverse()), replacement.reverse()).reverse();
};

function shrinkImages() {
    var elem = document.getElementsByTagName("img");
    for(var i = 0; i < elem.length; i++)
    {
        if(elem[i].offsetWidth>650) {
            var aspect = elem[i].offsetWidth / elem[i].offsetHeight;
            elem[i].style.width = "650px";
            elem[i].style.height = (650/aspect) + "px";
        }
    } 
}

function doBattle(oid, cid) {
    document.getElementById("battlechart").innerHTML='<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0" width="100%" height="460" id="Battle Chart"><param name="allowScriptAccess" value="always" /><param name="bgcolor" value="#ffffff" /><param name="movie" value="/charts/MSColumnLine3D.swf"/><param name="FlashVars" value="&chartWidth=100%&chartHeight=460&debugMode=0&dataURL=%2Fchart.php%3Fa%3D' + oid + '%26b%3D' + cid + '&registerWithJS=1" /><param name="quality" value="high" /><param name="wmode" value="window" /><embed src="/charts/MSColumnLine3D.swf" bgcolor="#ffffff" FlashVars="&chartWidth=100%&chartHeight=460&debugMode=0&dataURL=%2Fchart.php%3Fa%3D' + oid + '%26b%3D' + cid + '&registerWithJS=1" quality="high" width="100%" height="460" name="Battle Chart" allowScriptAccess="always" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" wmode="window" /></object>';
    return false;
}

function switchType(type) {
    if(type == 1) {
        if(document.getElementById("pointsFinal") != null) {
            document.getElementById("pointsFinal").style.display = "inline";
            document.getElementById("pointsSemi").style.display = "none";
        }
        if(document.getElementById("videoFinal") != null) {
            document.getElementById("videoFinal").style.display = "inline";
            document.getElementById("videoSemi").style.display = "none";
        }
        if(document.getElementById("pointsReceived") != null) {
            document.getElementById("pointsReceived").style.display = "inline";
            document.getElementById("pointsGiven").style.display = "none";
        }
    } else {
        if(document.getElementById("pointsFinal") != null) {
            document.getElementById("pointsFinal").style.display = "none";
            document.getElementById("pointsSemi").style.display = "inline";
        }
        if(document.getElementById("videoFinal") != null) {
            document.getElementById("videoFinal").style.display = "none";
            document.getElementById("videoSemi").style.display = "inline";
        }
        if(document.getElementById("pointsReceived") != null) {
            document.getElementById("pointsReceived").style.display = "none";
            document.getElementById("pointsGiven").style.display = "inline";
        }
    }
}
function resizeIframeToFitContent(id, increase) {
    var newheight;
    originalIFrame = parseInt(document.getElementById(id).height);
    if(document.getElementById){
    newheight=document.getElementById(id).contentWindow.document.body.scrollHeight;
    }
    if(newheight <= originalIFrame) {
        document.getElementById(id).style.overflowY="hidden";
        document.getElementById(id).contentWindow.document.body.overflowY="hidden";
    }
}

function updateNews(req) {
	var body = req.responseText;
 	var reps = 0;
 	/*while(body.indexOf("<a href") != -1) {
 		body = body.replace("<a href", "<a onclick='return ajaxNav(this);' href");
 		reps++;
 	}*/
	document.getElementById("latestNews").innerHTML = body;
    done = true;
}

function updatePosts(req) {
	var body = req.responseText;
 	var reps = 0;
 	/*while(body.indexOf("<a href") != -1) {
 		body = body.replace("<a href", "<a onclick='return ajaxNav(this);' href");
 		reps++;
 	}*/
	document.getElementById("latestPosts").innerHTML = body;
}

function fixHeight(force) {
	if(isSet) return;
    force = true;
	isSet = false;
    if(document.getElementById("rightbox") == null) return;
	var currentHeight = 977;//document.getElementById('rightbox').offsetHeight - 1219;
	var desiredHeight = 0;
    if(document.getElementById('XFPage') != null) desiredHeight = document.getElementById('XFPage').offsetHeight - 1219;
	if(oCurrentHeight == 0) {
		oCurrentHeight = currentHeight;
	}
	if(force) {
		currentHeight = oCurrentHeight;
		oldNews = 0;
		oldPosts = 0;
	}
	var numberToAdd = Math.floor((desiredHeight - currentHeight)/58);
	var numberToDivide = 0;
	if(numberToAdd>0) {
		numberToDivide = numberToAdd / 2;
		numberNews = numberPosts = (numberToDivide + 6);
		if(numberNews%2 != 0) {
			numberNews = Math.floor(numberNews) + 1;
			numberPosts = numberNews;
		}
        if(isHome) {
        numberPosts = numberToAdd + 6;
        numberNews = originalNews
        ;
        additionalOffset = 3;
        }
        if(numberNews<6) numberNews = 6;
        if(numberPosts<6) numberPosts = 6;
		if(oldNews < numberNews || oldPosts < numberPosts || force == true) {
            if(document.getElementById("latestNews") != null) {
                if(numberNews>=6) {
                    sendRequest('/blocks/block.LatestNews.php?items=' + numberNews + '&d=' + new Date().getTime(), updateNews);
                }
            }
            if(document.getElementById("latestPosts") != null) {
                if(numberPosts>=6 && typeof tzOffset != 'undefined') {
                    sendRequest('/blocks/block.LatestPosts.php?items=' + numberPosts + "&tz=" + tzOffset + '&d=' + new Date().getTime(), updatePosts);
                }
            }
		}
		oldNews = numberNews;
		oldPosts = numberPosts;
	} else {
            if(document.getElementById("latestNews") != null) {
                    sendRequest('/blocks/block.LatestNews.php?items=6&d=' + new Date().getTime(), updateNews);
            }
            if(document.getElementById("latestPosts") != null  && typeof tzOffset != 'undefined') {
                    sendRequest('/blocks/block.LatestPosts.php?items=6&tz=' + tzOffset + '&d=' + new Date().getTime(), updatePosts);
            }

    }
	var rightBoxHeight = document.getElementById('rightbox').offsetHeight - 1219;
	increment = desiredHeight - (rightBoxHeight)-36;
    if(force) {
        increment = (desiredHeight - (rightBoxHeight)-36 + 19);
        if(increment == 15) increment = 34;
    }
	if(force) {
        stopCheck = setInterval(checkHeight, 100); 
		document.getElementById('fill').style.height = "0px";
	}
        increment = increment + additionalOffset;
	if(increment <= 50 && increment > 0) {
		document.getElementById('fill').style.height = parseInt(document.getElementById('fill').style.height) + increment + "px";
	}
};

function checkHeight() {
    if((oldNews != originalNews || oldPosts != originalPosts) && increment < -10) {
        if(done) oldNews--;
        if(!checkedYet) {
            done = false;
            if(document.getElementById("latestNews") != null) {
                sendRequest('/blocks/block.LatestNews.php?items=' + oldNews + '&d=' + new Date().getTime(), updateNews);
            }
            checkedYet = true;
        }
       // if(done) checkedYet = false;
        var desiredHeight = document.getElementById('mainContent').offsetHeight - 1219;
        var rightBoxHeight = document.getElementById('rightbox').offsetHeight - 1219;
        increment = (desiredHeight - (rightBoxHeight)-36 + 19);
        if(increment == 15) increment = 34;

    } else {
        clearTimeout(stopCheck);
		document.getElementById('fill').style.height = "0px";
        if(increment <= 50 && increment > 0) {
            document.getElementById('fill').style.height = parseInt(document.getElementById('fill').style.height) + increment + "px";
        }
    }
}

$(document).ready(function() {
    if(screen.height < 600) {
        document.getElementById("positionbar1").style.position="absolute";
        document.getElementById("positionbar2").style.position="absolute";
    }
	var checkScroll = window.location.href.replace(/#!/g, "").indexOf("#");
	if(checkScroll != -1) {
		var anchor = window.location.href.replace(/#!/g, "").substring(checkScroll+1).replace("/","");
		if($("#"+anchor).length>0) {
			var positionCompensation = 0;
			if(document.getElementById("positionbar1").style.position == "fixed") positionCompensation = -60;
			$('html,body').animate({scrollTop: $("#"+anchor).offset().top + positionCompensation },'slow');
		}
	}
    

$("img.emo, img.mceSmilie").load(function(){
    if(apngNeeded) {
    var animated = false;
        if(this.src.indexOf("flashchat")>-1 && this.src.indexOf(".png")>-1) {
            animated = true;
            var oldWidth = this.clientWidth;
            var oldHeight = this.clientHeight;
            if(oldWidth > 0 && oldHeight > 0) {
                if(!$(this).attr("data-is-apng")) APNG.animateImage(this);
                this.style.height = oldHeight + "px";
                this.style.width = oldWidth + "px";
                $(this).css("width", oldWidth + "px !important");
                $(this).css("height", oldHeight + "px !important");
            }
        }
    if(animated) {
        $("canvas").each(function(){
            if(this.className != "chatEmo") if(0+parseInt(this.width)>0) $(this).css("width", parseInt(0+this.width) + "px");
        });
    }
    }
});

    ready = true;
    if(window.localStorage) {
    if(window.localStorage["resetCode"] != undefined) {
   		var x = document.getElementsByTagName("script");   
   		for(var i=0;i<x.length;i++)  
   		{  
   			if(x[i].src) {
   				if(((x[i].src.indexOf("ajax.js") == -1 && x[i].src.indexOf("newchat.js") == -1 && x[i].src.indexOf("escchat.js") == -1 && x[i].src.indexOf("newchat-public.js") == -1 && x[i].src.indexOf("jquery.contextMenu.js") == -1 && x[i].src.indexOf("soundmanager2.js") == -1 && x[i].src.indexOf("flexcroll.js") == -1 && x[i].src.indexOf("emoticons.js.php") == -1 && x[i].src.indexOf("dynamic.js.php") == -1  && x[i].src.indexOf("session.js.php") == -1)) && x[i].src.indexOf("escchat.com")>-1) {
                    if(!window.localStorage[x[i].src]) {
                        var urlAddress = x[i].src;
                        if(urlAddress.indexOf("?") > -1) {
                            urlAddress += "&ts=" + new Date().getTime();
                        } else {
                            urlAddress += "?ts=" + new Date().getTime();
                        }
                        $.get(urlAddress, function(data)  {
                            var urlRetrieved = this.url;
                            urlRetrieved = urlRetrieved.substring(0, urlRetrieved.lastIndexOf("ts=")-1);
                            window.localStorage[urlRetrieved] = data;
                        }, false, "html");
                    }
   				}
   			}
   		}
        var jQ = "http://www.escchat.com/js/jquery/jquery-1.5.2.min.js";
        if(!window.localStorage[jQ]) {
            $.get(jQ, function(data)  {  window.localStorage[this.url] = data; }, false, "html");
        }
    }
    }
    shrinkImages();
});

$(window).load(function() {
    setTimeout(function() { fixHeight(true); }, 333);
});

var chatIlluminated = false;
$(function(){
   if($("#chatmenu").hasClass('active')) chatIlluminated = true;
   $("#chatballoon").hover(
        function(){
            if(!chatIlluminated)
            $("#chatmenu").addClass('active');
        },
        function(){
            if(!chatIlluminated)
            $("#chatmenu").removeClass('active');
        }
    );
});

function switchPoll(category, pollName) {
    var categoryNumber = parseInt(category);
    sendRequest('/blocks/block.Poll.php?c=' + categoryNumber + "&p=" + pollName, updatePoll);
}

function updatePoll(req) {
	var body = req.responseText;
 	var reps = 0;
 	while(body.indexOf("<a href") != -1) {
 		body = body.replace("<a href", "<a onclick='return ajaxNav(this);' href");
 		reps++;
 	}
    document.getElementById("poll-container").innerHTML = body;
}

function updateBlocks() {
    // Countdown
    if(document.getElementById("countdown") != null) {
    var countdown = document.getElementById("countdown").innerHTML;
    var daysStart = countdown.indexOf("<!-- ") + 5;
    var daysEnd = countdown.indexOf(" -->", daysStart); 
    var currentDays = countdown.substring(daysStart, daysEnd);
    $.get("/blocks/block.Countdown.php?d=" + new Date().getTime(), function(data) {
        daysStart = data.indexOf("<!-- ") + 5;
        daysEnd = data.indexOf(" -->", daysStart); 
        var newDays = data.substring(daysStart, daysEnd);
        if(currentDays != newDays) {
            document.getElementById("countdown").innerHTML = '<li class="last">' + data + '</li>';
        }
    });
    }
    // Stats bar
    if(document.getElementById("statsbar") != null) {
        $.get("/blocks/block.StatsBar.php?d=" + new Date().getTime(), function(data) {
            document.getElementById("statsbar").innerHTML = data;
        });
    }
    // Forum posts and news
    fixHeight(true);
    
    // Homepage/chat forum posts
    if(document.getElementById("homePostBox") != null) {
        var homePosts = document.getElementById("homePostBox").innerHTML;
        var checksumStart = homePosts.indexOf("<!-- ") + 5;
        var checksumEnd = homePosts.indexOf(" -->", checksumStart); 
        var currentChecksum = homePosts.substring(checksumStart, checksumEnd);

        $.get("/blocks/block.HomeLatestPosts.php?ts=1&d=" + new Date().getTime(), function(data) {
            checksumStart = data.indexOf("<!-- ") + 5;
            checksumEnd = data.indexOf(" -->", checksumStart); 
            var newChecksum = data.substring(checksumStart, checksumEnd);
            if(currentChecksum != newChecksum) { 
                document.getElementById("homePostBox").innerHTML = data.replace(/\{TIMESTAMP\}/g, avatarTimestamp);
                if(ready) XenForo.init();
            }
        });
    }  
	if(document.getElementById("announcementballoon") != null && loggedID > 0) {
		$.get("/blocks/block.AnnouncementCounter.php?d=" + new Date().getTime(), function(announcementCount) {
            document.getElementById("announcementcount").innerHTML = announcementCount;
            if(announcementCount>0) {
                $("#announcementballoon").css("display", "block");
            } else {
                $("#announcementballoon").css("display", "none");
            }
        });
    }

    setTimeout(function() { updateBlocks(); }, 120000);
}

function updateBalloons(onetimeonly) {
    if(document.getElementById("ConversationsMenu_Counter") != null) {
        $.get("/blocks/block.Balloons.php?d=" + new Date().getTime(), function(data) {
            var counter = data.split(",");
            if(counter[0] == "0") {
                document.getElementById("ConversationsMenu_Counter").style.display = "none";
            } else {
                document.getElementById("ConversationsMenu_Counter").style.display = "inline";
            }
            if(counter[1] == "0") {
                document.getElementById("AlertsMenu_Counter").style.display = "none";
            } else {
                document.getElementById("AlertsMenu_Counter").style.display = "inline";
            }
            document.getElementById("ConversationsMenu_Counter").innerHTML = counter[0] + '<span class="arrow"></span>';
            document.getElementById("AlertsMenu_Counter").innerHTML = counter[1] + '<span class="arrow"></span>';
        });
    }
    if(!onetimeonly) setTimeout(function() { updateBalloons(); }, 15000);
}

		function initMediaPlayer(streamer, url, play) {
            var init = "";
            var vol = "";
                img = "image: '/images/spacer.png',";
			if(streamer == undefined) {
				streamer = "";
			} else {
				streamer = ", streamer: '" + streamer + "' ";              
                init = "initMediaPlayer();";  
            }
			if(url == undefined) {
				url = "/player.flv";
                vol = "jwplayer('mediaplayer').setVolume(100);";
                img = "image: '/images/" + skin + "/mediaplayer.png',";
			}
            eval("jwplayer('mediaplayer').setup({players: [{type: 'flash', src:'/mediaplayer.swf'}], file: '" + url + "'" + streamer + ", " + img + " 'screencolor': '1d1d1d', 'backgroundcolor': '1d1d1d', controlbar: 'over', skin: '/mediaskin.zip', 'controlbar.idlehide': 'true', 'youtube.quality': 'medium', events: { onReady: function() { playerLoaded = true; playerPlaying = false; " + vol + "jwplayer('mediaplayer').setMute(isMuted); if(play) jwplayer('mediaplayer').play();},onBuffer: function() { bufferTime(e); }, onPlay: function() {jQuery.noData={}; if(jwplayer('mediaplayer').getVolume() == 0 && !isMuted) jwplayer('mediaplayer').setVolume(100); clearTimeout(bufferClock); playerPlaying = true; if(pinPlayer) resizePlayer(true, 0);}, onIdle: function() {playerPlaying = false; jwplayer('mediaplayer').setFullscreen(false); resizePlayer(false);" + init + "}}});");
		}
        
function playSoundClip(data) {
        var data2 = data;
        if(data.indexOf("?")>-1) data2 = data.substring(0, data.indexOf("?"));
        if(data2.indexOf("login") == -1 && data2.indexOf("bell") == -1) {
            data = data2;
        } else {
            for(k in soundManager.sounds) {
                var key = soundManager.createSound({id: k}).url;
                key = key.substring(key.indexOf("/sounds"));
                if(key.indexOf("?")>-1) {
                    var userID = parseInt(key.substring(key.lastIndexOf("/")+1));
                    if(userID == parseInt(data.substring(data.lastIndexOf("/")+1))) {
                        if((key.indexOf("bell")>-1 && data.indexOf("bell")>-1) || (key.indexOf("login")>-1 && data.indexOf("login")>-1)) {
                            if(data != key) {
                                soundManager.destroySound(data2);
                            }
                            break;
                        }
                    }
                }
            }
        }
        createSoundClip(data2, "http://www.escchat.com" + data);
        soundManager.play(data2);
}

function scrollbarWidth() { 
   	 var div = $('<div style="width:50px;height:50px;overflow:hidden;position:absolute;top:-200px;left:-200px;"><div style="height:100px;"></div>'); 
     $('body').append(div); 
     var w1 = $('div', div).innerWidth(); 
     div.css('overflow-y', 'scroll'); 
     var w2 = $('div', div).innerWidth(); 
     $(div).remove(); 
     return (w1 - w2); 
}

function createSoundClip(fileID, fileURL) {
    if(smReady) {
        soundManager.createSound({
            id: fileID,
            url: fileURL,
            autoLoad: true
        });
    } else {
        soundsToLoad[fileID] = fileURL;
    }
}

soundManager.url = '/js/';
soundManager.autoLoad = true;
soundManager.preferFlash = true;
soundManager.useHTML5Audio = true;
soundManager.flashLoadTimeout = 0;
soundManager.onready(function () {

    smReady = true;
    
    createSoundClip("/sounds/pvtsend.mp3", "http://www.escchat.com/sounds/pvtsend.mp3");
    createSoundClip("/sounds/pvtrecv.mp3", "http://www.escchat.com/sounds/pvtrecv.mp3");
        
    for (file in soundsToLoad) {
        createSoundClip(file, soundsToLoad[file]);
    }
    
	if(soundToPlay != "") {
		playSoundClip(soundToPlay);
	}
    
});

updateBlocks();
updateBalloons();

window.addEventListener('keydown', function(e) {
if(e.keyCode == 27) {
    e.preventDefault()
}
})


function animatePNGs() {
    if(!apngNeeded) return;
    var animated = false;
    $("img.emo, img.mceSmilie, img.smilie").each(function(){
        if(this.src.indexOf("flashchat")>-1 && this.src.indexOf(".png")>-1) {
            animated = true;
            var oldWidth = this.clientWidth;
            var oldHeight = this.clientHeight;
            if(oldWidth > 0 && oldHeight > 0) {
                if(!$(this).attr("data-is-apng")) APNG.animateImage(this);
                this.style.height = oldHeight + "px";
                this.style.width = oldWidth + "px";
                $(this).css("width", oldWidth + "px !important");
                $(this).css("height", oldHeight + "px !important");
            }
        }
        
    });
    if(animated) {
        $("canvas").each(function(){
            if(this.className != "chatEmo") if(0+parseInt(this.width)>0) $(this).css("width", parseInt(0+this.width) + "px");
        });
    }
};

function apngCheck() {
	var apngTest = new Image();
    apngNeeded = true;
	var ctx = document.createElement("canvas").getContext("2d");
	apngTest.onload = function () {
		ctx.drawImage(apngTest, 0, 0);
		var result = ( ctx.getImageData(0, 0, 1, 1).data[3] === 0 );
        if(result) apngNeeded = false;
	};
	apngTest.src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAACGFjVEwAAAABAAAAAcMq2TYAAAANSURBVAiZY2BgYPgPAAEEAQB9ssjfAAAAGmZjVEwAAAAAAAAAAQAAAAEAAAAAAAAAAAD6A+gBAbNU+2sAAAARZmRBVAAAAAEImWNgYGBgAAAABQAB6MzFdgAAAABJRU5ErkJggg==";
};

function bannerRotation() {
			$.featureList(
				$("#tabs li a"),
				$("#output li"), {
					start_item	:	0
				}
			);
			$("ul#output li img").fadeIn();
};    
setInterval(function() { animatePNGs(); }, 1000);        
