/*
<br><br>
Ajax routines for escChat.com
<br><br>
Copyright (c) jw. All rights reserved.
<br><br>
Any analysis or copying of this source code by any means, whether human or otherwise
for any purpose whatsoever, such as to discover internal operation details or modify
the code to alter it's behaviour is strictly forbidden as all codes are protected by
copyright outlined by the Copyright, Designs and Patents Act 1988 under English law.
All violations are taken seriously and action will be taken against any offenders to
the maximum extent permitted under civil law. Please don't steal my code! Thank you.
<br><br>
*/

var sessionTimer = "";
var pagesNavigated = 0;
var buttonAction;
var newAction = "";
var init = false;
var connected = false;
var lastAjax = "GET";
var lastURL = "";
var pageTitle = document.title;
var hasFocus = true;
var pageFocus = true;
var focus1 = true;
var focus2 = false;
var focus3 = false;
var forceNormalNavigation = false;
var inChat = false;
var playerLoaded = false;
var full = false;
var timeoutEnded = false;
var scriptsLoaded = {};
if(ieFail) useNormalNavigation = true;
if(forceNormalNavigation) useNormalNavigation = true;
var latestPage = "";
var pathName = window.location.pathname;
function sendRequest(url, callback, postData) {
	lastURL = window.location.href;
	var req = createXMLHTTPObject();
	if (!req) return;
	var method = (postData) ? "POST" : "GET";
	req.open(method,url,true);
	//req.setRequestHeader('User-Agent','XMLHTTP/1.0');
	if (postData) {
		req.setRequestHeader('Content-type','application/x-www-form-urlencoded');
		req.setRequestHeader("Content-length", postData);
		req.setRequestHeader("Connection", "close");
	}
	req.onreadystatechange = function () {
		if (req.readyState != 4) return;
		if (req.status != 200 && req.status != 304) {
			//alert('HTTP error ' + req.status);
			return;
		}
		callback(req);
	}
	if (req.readyState == 4) return;
	req.send(postData);
}

var XMLHttpFactories = [
	function () {return new XMLHttpRequest()},
	function () {return new ActiveXObject("Msxml2.XMLHTTP")},
	function () {return new ActiveXObject("Msxml3.XMLHTTP")},
	function () {return new ActiveXObject("Microsoft.XMLHTTP")}
];

function createXMLHTTPObject() {
	var xmlhttp = false;
	for (var i=0;i<XMLHttpFactories.length;i++) {
		try {
			xmlhttp = XMLHttpFactories[i]();
		}
		catch (e) {
			continue;
		}
		break;
	}
	return xmlhttp;
}

function dummy() {
}

function changePageAjax(p, ignore) {
if(inChat && !ignore) {
	if(typeof window.history.pushState == 'function') { 
		window.history.pushState("", "", "http://www.escchat.com/chat/enter");
	} else {
		window.location.hash = "!/chat/enter";
	}
	return false;
}
if(connected) socket.write("ACTIVITY");
	$("#AccountMenu").hide();
	$("#ConversationsMenu").hide();
	$("#AlertsMenu").hide();
	$(".formPopup").hide();
	$('li').each(function() {
		if($(this).hasClass("PopupOpen")) {
			$(this).removeClass("PopupOpen");
			$(this).addClass("PopupClosed");
		}
	});
if(!useNormalNavigation) {
pagesNavigated++;
var url = p;
if(url.lastIndexOf("#")>-1 && (url.lastIndexOf("#") != url.indexOf("#!"))) {
	p = url.substring(0, url.lastIndexOf("#"));
}
lastAjax = "GET";
if(p == "http://www.escchat.com" || p == "http://www.escchat.com/") {
	isHome = true;
} else {
	isHome = false;
}
if(typeof window.history.pushState == 'function') { 
	window.history.pushState("", "", url);
} else {
	pathName = url.replace("http://www.escchat.com/", "");
	window.location.hash = "!/" + pathName;
}
latestPage = window.location.href;
} else {
	window.location = window.location.href.replace("/#!/", "/");
}    
sendRequest(p, changedPageAjax);
}

function postPageAjax(p, data) {
if(connected) socket.write("ACTIVITY");

	$("#AccountMenu").hide();
	$("#ConversationsMenu").hide();
	$("#AlertsMenu").hide();
	$(".formPopup").hide();

var url = p;
if(url.lastIndexOf("#")>-1 && (url.lastIndexOf("#") != url.indexOf("#!"))) {
	p = url.substring(0, url.lastIndexOf("#"));
}
lastAjax = "POST";
if(p.indexOf("add-reply") > -1 || p.indexOf("insert-reply") > -1) {
	if(typeof window.history.pushState == 'function') { 
		window.history.pushState("", "", p);
	} else {
		pathName = p.replace("http://www.escchat.com/", "");
		window.location.hash = "!/" + pathName;
	}
	latestPage = window.location.href;
} else {
	latestPage = "/" + p.replace("/save", "");
}
sendRequest(p, changedPageAjax, data);
}

window.onpopstate = function (event) {
		if(init && latestPage != window.location.href && latestPage != "") {
			changePageAjax(window.location.href);
      }	
}

window.onhashchange = function (event) {
		if(init && latestPage != window.location.href) {
			var url = window.location.href;
			var hashBit = url.indexOf("#!/");
			if(hashBit > -1) {
	     		changePageAjax("http://www.escchat.com/" + url.substring(hashBit+3));
	     	} else {
	     		changePageAjax(window.location.href);
	     	}
      }	
}

function changedPageAjax(data) {
	if(forceNormalNavigation) return;
	var html = data.responseText;
	full = false;
    timeoutEnded = false;
	if(html.indexOf("homebar.css") > -1 && lastAjax == "POST") {

    	var url = lastURL;
        var hashBit = url.indexOf("#!/");
        if (hashBit > -1) {
    		url = "http://www.escchat.com/" + url.substring(hashBit+3);
        }
        url = url.replace("create-thread", "").replace("add-reply", "");
        changePageAjax(url);
        return false;
	}

	var can1 = html.indexOf('<link rel="canonical"');
	var can2 = 0;
	var canonical = "";
	if(can1 > -1) {
		can2 = html.indexOf('"', can1+28);
		canonical = html.substring(can1+28, can2);
		if(lastURL.indexOf("add-reply")>-1) canonical += "#newpost";
		if(lastURL.indexOf("insert-reply")>-1) canonical += "#newpost";
		if(latestPage.indexOf("/conversations/")>-1 && latestPage.indexOf("?m=")>-1) {
			canonical += "#message-" + parseInt(latestPage.substring(latestPage.indexOf("?m=")+3));
		}		
		if(latestPage.indexOf("/posts/")>-1) {
			canonical += "#post-" + latestPage.substring(latestPage.indexOf("/posts/")+7).replace("/", "");
		}
		if(latestPage.indexOf("/profile-posts/")>-1) {
			canonical += "#profile-post-" + latestPage.substring(latestPage.indexOf("/profile-posts/")+15).replace("/", "");
		}
		if(latestPage.lastIndexOf("#")>-1 && (latestPage.indexOf("#!") != latestPage.lastIndexOf("#"))) {
			canonical += latestPage.substring(latestPage.indexOf("#")).replace("/", "");
		}
	if(window.location.href.substring(window.location.href.length-7) == "/unread") {
		updateBalloons(true);
		var messageID = html.lastIndexOf('<div id="likes-');
		if(messageID>-1) {
			var messageIDend = html.indexOf('"', messageID + 15);
			var unreadAnchor = "#" + html.substring(messageID + 15, messageIDend);
			setTimeout(function() { var positionCompensation = 0;
			if(document.getElementById("positionbar1").style.position == "fixed") positionCompensation = -60;
			setTimeout(function() { $('html,body').animate({scrollTop: $(unreadAnchor).offset().top + positionCompensation },'slow');}, 250); }, 500);
		}
	}
		if(canonical.substring(canonical.length-6) == "delete") canonical = canonical.substring(0, canonical.length-6);

		if(typeof window.history.pushState == 'function') { 
			window.history.replaceState("", "", canonical);
		} else {
			pathName = canonical.replace("http://www.escchat.com/", "");
			window.location.hash = "!/" + pathName;
		}
		
		latestPage = window.location.href;
		socket.write("URL " + latestPage);
	}

	var bodyS1 = html.indexOf("<head>");
	var bodyE1 = html.indexOf("</head>");
	var bodyS2 = html.indexOf("<div id=\"XFContainer\">");
	var bodyE2 = html.indexOf("<!-- End of container -->");
	var body = html.substring(bodyS1+6, bodyE1) + html.substring(bodyS2+22, bodyE2);

	body = body.replace("</head>", "");
	body = body.replace("<body>", "");
	body = body.replace("</body>", "");
	var titleS = html.indexOf("<title>");
	var titleE = html.indexOf("</title>");
	var title = Encoder.htmlDecode(html.substring(titleS+7, titleE));
 	document.title = title;
 	pageTitle = title;
 	unreadCounter();
  	body = body.replace("dynamic.js.php", "blank.js");
  	body = body.replace("emoticons.js.php", "blank.js");
  	body = body.replace("ajax.js", "blank.js");
  	body = body.replace("jquery/jquery.xenforo.rollup.js", "blank.js");
  	body = body.replace("xenforo/full/xenforo.js", "blank.js");

  	//body = body.replace("//ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js", "/js/jquery/jquery-1.5.2.min.js");
 	body = body.replace("<script type=\"text/javascript\" src=\"/ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js\"></script>", "");
 	body = body.replace("<script type=\"text/javascript\" src=\"/js/jwplayer.min.js\"></script>", "");
 	body = body.replace("<script type=\"text/javascript\" src=\"/js/jquery.tablesorter.min.js\"></script>", "");
 	body = body.replace("<script type=\"text/javascript\" src=\"/ckeditor/ckeditor.js\"></script>", "");
 	body = body.replace("<script type=\"text/javascript\" src=\"/js/webSocket.js\"></script>", "");
 	body = body.replace("<script type=\"text/javascript\" src=\"/js/jSocket.js\"></script>", "");
 	body = body.replace("<script type=\"text/javascript\" src=\"/js/openUrl.js\"></script>", "");
 	body = body.replace("<script type=\"text/javascript\" src=\"/js/newchat.js\"></script>", "");
 	body = body.replace("<script type=\"text/javascript\" src=\"/js/newchat-public.js\"></script>", "");
 	body = body.replace("<script type=\"text/javascript\" src=\"/js/apng-canvas.min.js\"></script>", "");
 	body = body.replace("<script type=\"text/javascript\" src=\"/js/cufon-yui.js\"></script>", "");
 	body = body.replace("<script type=\"text/javascript\" src=\"/js/cufon-replace.js\"></script>", "");
 	body = body.replace("<script type=\"text/javascript\" src=\"/js/Bebas_400.font.js\"></script>", "");
 	body = body.replace("<script type=\"text/javascript\" src=\"/js/player.js\"></script>", "");
 	body = body.replace("<script type=\"text/javascript\" src=\"/js/flash.js\"></script>", "");
 	body = body.replace("<script type=\"text/javascript\" src=\"/js/mousewheel.js\"></script>", "");
 	body = body.replace("<script type=\"text/javascript\" src=\"/js/swfobject.js\"></script>", "");
 	body = body.replace("<script type=\"text/javascript\" src=\"/js/encode.js\"></script>", "");
 	body = body.replace("<script type=\"text/javascript\" src=\"/js/flexcroll.js\"></script>", "");
 	body = body.replace("<script type=\"text/javascript\" src=\"/js/soundmanager2.js\"></script>", "");
 	body = body.replace("<script type=\"text/javascript\" src=\"/js/scrollpane.js\"></script>", "");
 	body = body.replace("<script type=\"text/javascript\" src=\"/js/smartspinner.js\"></script>", "");
 	body = body.replace("<script type=\"text/javascript\" src=\"/js/fancybox.js\"></script>", "");
 	body = body.replace("<script type=\"text/javascript\" src=\"/js/jquery.contextMenu.js\"></script>", "");
 	body = body.replace("<script type=\"text/javascript\" src=\"/js/jquery.featureList-1.0.0.js\"></script>", "");

	while(body.indexOf("<script type=\"text/javascript\" src=\"/js/blank.js")>-1) {
		var start = body.indexOf("<script type=\"text/javascript\" src=\"/js/blank.js");
		var end = body.indexOf("</script>", start);
		var string = body.substring(start, end);
		body = body.replace(string, "");
	}
	body = body.replace("<!----></div> </div> </div>", "");
	while(body.indexOf("<span id=\"newpost\"></span>") < body.lastIndexOf("<span id=\"newpost\"></span>")) {
		body = body.replace("<span id=\"newpost\"></span>", "");
	}
		var scriptText = "";	

		var scriptArray = new Array();
		var d = document.createElement("div");
		d.innerHTML = body;
   		var x = d.getElementsByTagName("script");   
   		for(var i=0;i<x.length;i++)  
   		{  
   			if(x[i].src) {
   				if((x[i].src.indexOf("?") == -1 || x[i].src.indexOf("?_v=6ec63d96") > -1) && x[i].src.indexOf("escchat.com")>-1 ) {
                    if(!scriptsLoaded[x[i].src]) {
                    if(window.localStorage) {
                        if(!window.localStorage[x[i].src]) {
                            scriptArray[scriptArray.length] = x[i].src;
                            scriptText +='<script type="text/javascript" src="' + x[i].src + '"></script>';
                        } else {
                            scriptText +='<script type="text/javascript">eval(window.localStorage["' + x[i].src + '"]);</script>';				
                        }
                    } else {
                        scriptArray[scriptArray.length] = x[i].src;
                        scriptText +='<script type="text/javascript" src="' + x[i].src + '"></script>';
                    }
                    if(x[i].src.indexOf("tiny_mce.js")==-1) scriptsLoaded[x[i].src] = true;
                    }
   				}
   			}
   		}
   		//body = body.replace(/<script\b[^>]*>(.*?)<\/script>/ig, "");

	$(".xenTooltip").hide();
	var originalNews = 6;
	var originalPosts = 6;
	var oldNews = originalNews;
	oldPosts = originalPosts;
	isSet = false;
	increment = 0;
	finalCheck = false;
	oCurrentHeight = 0;
	originalIFrame = 0;
	additionalOffset = 0;
	checkedYet = false;
	done = true;
	if(typeof(ncDoc) != "undefined") {
		if(ncDoc.getElementById("chatText") != null && document.getElementById('newchat') != null) {
			socket.write("LEFTCHAT");
			inChat = false;
			nowChatting = false;
            timeoutEnded = false;
		}
	}
		//$("#XFContainer").html(body);
		var XFPageStart = body.indexOf("<div id=\"XFPage\">")+17;
		var XFPageEnd = body.indexOf("</section", XFPageStart)-10;
		var jsStart = body.indexOf("jQuery.extend");
		var jsEnd = body.indexOf("</script>", jsStart);
		playerLoaded = false;
		playerPlaying = false;
		$("#XFPage").html(scriptText + body.substring(XFPageStart, XFPageEnd) + '<script type="text/javascript">' + body.substring(jsStart, jsEnd) + '; XenForo.init(); $(".facebookLike").each(function() { FB.XFBML.parse(this); } ); if(isHome) bannerRotation();</script>');
		if(document.getElementById("chattingNow") != null || enteredChatNow) {
			if(document.getElementById("rightbox") != null) {
				var sideBarStart = body.indexOf('<div id="rightbox">') + 19;
				var sideBarEnd = body.indexOf('</aside>', sideBarStart) - 49;
				$("#rightbox").html(body.substring(sideBarStart, sideBarEnd));
	    		Cufon.refresh();
			}
			enteredChatNow = false;
		}

    	if(document.getElementById("chattingnowheader") != null) {
    		updateChatCounter();
	    }

		
		if(document.getElementById("sort") != null) {
			$("#sort").tablesorter();   
		}
		if(window.localStorage) {
        if(window.localStorage["resetCode"] != undefined) {
			for(var i=0; i<scriptArray.length; i++) {
				$.get(scriptArray[i], function(data) { window.localStorage[this.url] = data;}, false, "html");
			}
		}
        }
		document.getElementById("homemenu").className = "";
		document.getElementById("chatmenu").className = "";
		document.getElementById("newsmenu").className = "";
		document.getElementById("forummenu").className = "";
		document.getElementById("escmenu").className = "";
		document.getElementById("pastmenu").className = "";
		document.getElementById("statsmenu").className = "";
		document.getElementById("contestmenu").className = "";
		if(body.indexOf('id="homemenu" class="active topMenu"')>-1) {
			document.getElementById("homemenu").className = "active topMenu";
		} else if(body.indexOf('id="chatmenu" class="active topMenu"')>-1) {
			document.getElementById("chatmenu").className = "active topMenu";
		} else if(body.indexOf('id="newsmenu" class="active topMenu"')>-1) {
			document.getElementById("newsmenu").className = "active topMenu";
		} else if(body.indexOf('id="forummenu" class="active topMenu"')>-1) {
			document.getElementById("forummenu").className = "active topMenu";
		} else if(body.indexOf('id="escmenu" class="active topMenu"')>-1) {
			document.getElementById("escmenu").className = "active topMenu";
		} else if(body.indexOf('id="pastmenu" class="active topMenu"')>-1) {
			document.getElementById("pastmenu").className = "active topMenu";
		} else if(body.indexOf('id="statsmenu" class="active topMenu"')>-1) {
			document.getElementById("statsmenu").className = "active topMenu";
		} else if(body.indexOf('id="contestmenu" class="active topMenu"')>-1) {
			document.getElementById("contestmenu").className = "active topMenu";
		}

	//document.getElementById("XFContainer").innerHTML = body;
    shrinkImages();
	setTimeout(function() { fixHeight(true); }, 500);
	setTimeout(function() { fixHeight(true); }, 5000);
    
	scroll(0,0);
	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) {
		setTimeout(function() { 
			var positionCompensation = 0;
			if(document.getElementById("positionbar1").style.position == "fixed") positionCompensation = -60;
			if($("#"+anchor).offset().top <=0) {
				$('html,body').animate({scrollTop: $("#"+anchor + "div").offset().top + positionCompensation },'slow');
			} else {
				$('html,body').animate({scrollTop: $("#"+anchor).offset().top + positionCompensation },'slow');
			}
		}, 500);
		}
	}
	

	Cufon.refresh();
}

function ajaxNavPopup(link, e) {
	if(useNormalNavigation) { window.location = link; return true; }
	$("#AccountMenu").hide();
	$("#ConversationsMenu").hide();
	$("#AlertsMenu").hide();
	$(".formPopup").hide();
	$('li').each(function() {
		if($(this).hasClass("PopupOpen")) {
			$(this).removeClass("PopupOpen");
			$(this).addClass("PopupClosed");
		}
	});
	if(link.indexOf("/members/") != -1) { return true; }
	var hostname = window.location.hostname;
	hostname = hostname.replace("www.","").toLowerCase();
	var href = link.toLowerCase();
	var check = (href.indexOf("http://")!=-1 && href.indexOf(hostname)==-1) ? false : true;			
	if(!check)  { window.location = link; return true; }	
	changePageAjax(link);
	return useNormalNavigation;		
};

function ajaxNav(obj){
	if(useNormalNavigation) return true;
	if(obj.target == "_blank") return true;
	if(obj.href.indexOf("javascript:")!=-1) return true;
	$("#AccountMenu").hide();
	$("#ConversationsMenu").hide();
	$("#AlertsMenu").hide();
	$(".formPopup").hide();
	$('li').each(function() {
		if($(this).hasClass("PopupOpen")) {
			$(this).removeClass("PopupOpen");
			$(this).addClass("PopupClosed");
		}
	});
	var hostname = window.location.hostname;
	hostname = hostname.replace("www.","").toLowerCase();
	var check = (obj.href.indexOf("http://")!=-1 && obj.href.indexOf(hostname)==-1) ? false : true;		
	if(!check) return true;
	if(obj.href != null && obj.href != "http://www.escchat.com/#" && obj.href.indexOf("/logout/") == -1) {
		var proceed = true;
		var classList = obj.className.split(/\s+/);
		var classBuilder = "";
		for (i = 0; i < classList.length; i++) {
			if (classList[i] === 'PageNavNext') proceed = false;
			if (classList[i] === 'PageNavPrev') proceed = false;
			if (classList[i] === 'mp3') proceed = false;
			if (classList[i] === 'fancybox') proceed = false;
  			if (classList[i] === 'ul') proceed = false;  			
			if (classList[i] === 'avatar') proceed = false;
  			if (classList[i] === 'smallavatar') proceed = false;
  			if (classList[i] === 'EditControl') proceed = false;
  			if (classList[i] === 'OverlayTrigger') proceed = false;
  			if (classList[i] === 'username') proceed = false;
  			if (classList[i] === 'chat') proceed = false;
  			if (classList[i] === 'LikeLink') proceed = false;
  			if (classList[i] === 'MessageLoader') proceed = false;
  			if (classList[i] === 'FollowLink') proceed = false;  			
  			if (classList[i] === 'UnfollowLink') proceed = false;  			
  			if (classList[i] === 'BlockLink') proceed = false;  	
  			if (classList[i] === 'UnblockLink') proceed = false; 
  			if (classList[i] === 'ReadToggle') proceed = false;  			
  			if (classList[i] === 'DismissCtrl') proceed = false;  			
  			if (classList[i] === 'NoticeTab') proceed = false;  			
  			if (classList[i] === 'active') proceed = false;  			
  			if (classList[i] === 'CommentPoster') proceed = false;  			
  			if (classList[i] === 'CommentLoader') proceed = false;  			
  			if (classList[i] === 'postComment') proceed = false;
			if (classList[i] === 'LbTrigger') proceed = false;  			
			if (classList[i] === 'LbDateTime') proceed = false;  			
			if (classList[i] === 'LbContentLink') proceed = false;  			
			if (classList[i] === '_not_LbTrigger') proceed = false;  			
			if (classList[i] === 'SelectionCount') proceed = false; 
			if (classList[i] === 'imageNav') proceed = false;  			
			if (classList[i].indexOf('Lightbox')>-1) proceed = false;  			
  			if (classList[i] === 'privatechat') proceed = false;
  			if (classList[i] === 'mceButton') proceed = false;
  			if (classList[i] === 'NoOverlay') proceed = true;
  			if (classList[i] === 'topMenu') proceed = true;
  			classBuilder = classBuilder + classList[i] + " ";
		}
        if(obj.className == "nav ul") proceed = true;
		if(proceed) {
				changePageAjax(obj.href);
				return useNormalNavigation;
			}
	}
};

