// v1.9.98.99.6

//<xtag blob=wf.jquery.waterfall>

//var globalLastViewedForumId=urlParam('forumid',urlParam('fi','-1'))
var globalMaxForumPZT=0;
var loading= false;
var itemsLoaded=10;
var search_vanity = /^\/([^\/]+|[^\/]+\/[^\/]+)\/[-]*[0-9.]+\/.*/ ;
var search_vanityPZT = /^\/([^\/]+|[^\/]+\/[^\/]+)\/[-]*[0-9.]+\/[0-9]+\/.*/ ;


var urlParams;
(window.onpopstate = function () {
//	console.log(window.location);
	var match,
	pl     = /\+/g,  // Regex for replacing addition symbol with a space
	search = /([^&=]+)=?([^&]*)/g,
	decode = function (s) { return decodeURIComponent(s.replace(pl, " ")); },
	query  = window.location.search.substring(1);

	urlParams = {};
	while (match = search.exec(query))
		urlParams[decode(match[1])] = decode(match[2]);

	/*url encoded in the slash slash style */

	if(urlParams.length === undefined){
		if(/^.*\/([^\/]+|[^\/]+\/[^\/]+)\/[-]*[0-9.]+\/.*/.test(window.location.pathname)){
			var pztOffset=0;
			// vanity url format.  

			var bits=window.location.pathname.split('/');
			if(/^\/([^\/]+|[^\/]+\/[^\/]+)\/[-]*[0-9.]+\/[0-9.]+\/.*/.test(window.location.pathname)){
				// we have a pzt
				pztOffset=1;
				urlParams['pzt']=bits[bits.length-2];
			}
			var bits2=bits[bits.length-(2+pztOffset)].split('.');
			if(bits2.length>=3)urlParams['pi']=bits2[2];
			if(bits2.length>=2)urlParams['ti']=bits2[1];
			if(bits2.length>=1){
				urlParams['forumid']=bits2[0];
				urlParams['fi']=bits2[0];
			}
			
			// we also can hardcode the page and q params
			if(bits2.length<=1){
				urlParams['page']='wf';
				if(urlParams['fi']=='-1'){
					urlParams['q']='frontpage';
				}else if(urlParams['fi']=='0'){
					urlParams['q']='editorspicks';
				}else{
					urlParams['q']='forum';
				}
			}else{
				urlParams['page']='wf.forumpost';
				
			}

		}else{
			search = /([^\/-]+)-?([^\/]*)/g,
			query  = window.location.pathname;
			while (match = search.exec(query)){
				urlParams[decode(match[1])] = decode(match[2]);

			}
		}
	}

})();


if(parseInt(urlParam('wf.query_bLoB_s','0'))>0){
	itemsLoaded  = itemsLoaded + parseInt(urlParam('wf.query_bLoB_s','0'));
}else{
	itemsLoaded  = itemsLoaded + parseInt(urlParam('xwf.ft_bLoB_s','0'));
}

var itemsFetchCount=10;






// default function to return an empty string or default value.

function urlParam(){
	var param =arguments[0];
	var defaultV='';
	if(arguments.length==2){
		defaultV =arguments[1];
	}
	if(!urlParams)return defaultV;
	if(urlParams[param]){
		return urlParams[param];
	}else{
		return defaultV;
	}
}


/* Using the forum vist cookie to store the forum id and the date last visited (unixtimestamp)
 * This function highlights any new content by modifying the dom.
 * 
 * */
function handleNewForumContent(){
	if(!document.getElementById('wfForum'))return;
	var forumVisitsC=getCookie('forumVisit');

	if(forumVisitsC){
		if(forumVisitsC.indexOf(",") > -1 || forumVisitsC.indexOf("wf") > -1  || forumVisitsC.indexOf("//") > -1){	// fix an encoding error
			forumVisitsC= forumVisitsC.replace(/wfForumItem/g,'');
			forumVisitsC= forumVisitsC.replace('//','/');
			forumVisitsC= forumVisitsC.replace(/,/g,'/');
			setCookie('forumVisit', forumVisitsC,365);
		}

		// highlight the unvisited forums
		var forumVisits=forumVisitsC.split('/');

		for(n=0;n<forumVisits.length;n++){
			var fVisit=forumVisits[n].split(':');
			if(fVisit.length==2){
				// we have one 

				var f=document.getElementById('wfForumItem'+fVisit[0]);

				if(f!=null){
					var pz=f.getAttribute('data-pz');
					//console.log('db-pz: '+pz+' c:'+fVisit[1]+ ' fi:'+fVisit[0]);

					if(pz>0){
						var usePz=pz;

						if(pz>fVisit[1]  ){
							//if(n==0)console.log('db: '+pz+' c: '+fVisit[1]+ ' fi:'+fVisit[0]);
							// highlight it
							addClass(f.getElementsByTagName('span')[0],'glyphicon glyphicon-asterisk');
							usePz=fVisit[1];
							f.setAttribute('data-pz',fVisit[1]); // reset it to the last visit time
						}

						// now format it

						if(f.getElementsByTagName('a')[0].href.indexOf('&')>-1   ){
							//normal url
							f.getElementsByTagName('a')[0].href=f.getElementsByTagName('a')[0].href+'&pzt='+usePz; 
						}else{
							
							if(!/^.*\/([^\/]+|[^\/]+\/[^\/]+)\/[-]*[0-9.]+\/.*/.test(f.getElementsByTagName('a')[0].href)){

								f.getElementsByTagName('a')[0].href=f.getElementsByTagName('a')[0].href+'pzt-'+usePz+'/';	
							}else{
								// special vanity url - use just the numbers
								f.getElementsByTagName('a')[0].href=f.getElementsByTagName('a')[0].href+usePz+'/';	
							}		
						}

					}
					if(pz>globalMaxForumPZT) globalMaxForumPZT=pz;
				}
			};
		}
		forumVisitCookieMerge(forumVisits);  // check for new data
		forumVisits=null;
	}else{
		// build the forumVisitCookie
		var f = document.getElementsByClassName("wfForumItem");
		var fVisit='';
		for(n=0;n<f.length;n++){
			var id=f[n].getAttribute('id');
			id=id.replace('wfForumItem','');
			if(n>0)fVisit=fVisit+'/';
			fVisit=fVisit+id+':'+f[n].getAttribute('data-pz');
		}
		setCookie('forumVisit',fVisit,365);
	};
}


function forumVisitMarkAllAsRead(){
		var f = document.getElementsByClassName("wfForumItem");
		var fVisit='';
		for(n=0;n<f.length;n++){
			var id=f[n].getAttribute('id');
			id=id.replace('wfForumItem','');
			if(n>0)fVisit=fVisit+'/';
			fVisit=fVisit+id+':'+ globalMaxForumPZT;
		}
		setCookie('forumVisit',fVisit,365);

		handleNewForumContent();
}

/*function urlParam(sParam)
{
    var sPageURL = window.location.search.substring(1);
    var sURLVariables = sPageURL.split('&');
    for (var i = 0; i < sURLVariables.length; i++) 
    {
        var sParameterName = sURLVariables[i].split('=');
        if (sParameterName[0] == sParam) 
        {
            return sParameterName[1];
        }
    }
}*/

function getUrlParamerxxxxxxxxxxxx() { 
	var name =arguments[0];
	var defaultV='';
	if(arguments.length==2){
		defaultV =arguments[1];
	}
 	var x=defaultV;

 	//regular uri ?xxx=111&yyy=nnn
 	
  	if(window.location.search.length>0){
		x=decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.search)||[,""])[1].replace(/\+/g, '%20'))||defaultV;
  	}else{
   		// url in the / / / / format
  		// we have several of these the /xxx-nnn/ format or the custom vanity url format.  
  		// how to tell them apart....  
  		// /[^/]+/[0-9\.]+/*. /[^/]+/[^/]+/[0-9\.]+/*. are vanity
  		
  		if(/^\/([^\/]+|[^\/]+\/[^\/]+)\/[-]*[0-9.]+\/.*/.test(window.location.pathname)){
  			
  			// the vanity url format - we may have a pzt attached
  			
  			var pztOffset=0;
  			if(/^\/([^\/]+|[^\/]+\/[^\/]+)\/[-]*[0-9.]+\/[0-9.]+\/.*/.test(window.location.pathname)){
  				pztOffset=1;	
  			}
  			
  			var sURLVariables = window.location.pathname.split('/');
  			
  			
  				var sParameterName = sURLVariables[sURLVariables.length-(1+pztOffset)].split('.');
  				if (sParameterName.length>0 && (name == 'fi' || name == 'forumid')){
  					x= sParameterName[0];
  				}else if (sParameterName.length>1 && (name == 'ti' || name == 'threadid')){
  					x= sParameterName[1];
  				
  				}else if (sParameterName.length>2 && (name == 'pi' || name == 'postid')){
					x= sParameterName[2];  				
				}else if (name == 'pzt'){
					 	// this follows the encoded bit
					if(pztOffset==1){
						x= sParameterName[sParameterName.length-1];
					}
						
				}else if (sParameterName.length>0 && (name == 'q')){
					// deduced from the forum id
					if(sParameterName[0] == '-1'){
						x='frontpage';
					}else if(sParameterName[0] == '0'){
						x='editorspicks';
					}else if(sParameterName[0] == '-1'){
						x='forum';
					}
				}
  			  			
  		}else{
  			// regular named parameters in the // string
  			// do I have a vanity leader - may have to fix this....
  			var sURLVariables = window.location.pathname.split('/');
  			for (var i = 1; i < sURLVariables.length; i++) {
  				var sParameterName = sURLVariables[i].split('-');
  				if (sParameterName[0] == name){
  					x= sParameterName[1];
  				}
  			}
  		}

 	}
	//console.log('urlParam: '+window.location.pathname+' '+name+'='+x);

	return x 
}

/* this is called for each link on the forum list - and only then - it is run prior to calling the href*/
function updateForumVisitCookie(nextForumId,aTag){
    
    document.cookie =  'forumVisit=;expires=Thu, 01 Jan 1970 00:00:01 GMT; domain=www.watchprosite.com; path=/';  //cleanup errant cookies
    document.cookie =  'forumVisit=;expires=Thu, 01 Jan 1970 00:00:01 GMT; domain=www.watchprosite.com;';  //cleanup errant cookies
    //console.log(new Date(0).toUTCString());
	// do I need to wipe out new unanswered responses cookie
	var c=getCookie('pztSince');
	if(c){
		deleteCookie('pztSince');
		//aTag.href=aTag.href+"updpzt-"+ globalMaxForumPZT+'/';
	}
	if(globalMaxForumPZT==0)return;
	
	var currentForumId=urlParam('forumid',urlParam('fi','-1'));
	
	if(currentForumId==nextForumId)return;

	//forumId=globalLastViewedForumId;
	//globalLastViewedForumId=nextForumId;  // save this forum

	var forumVisitsC=getCookie('forumVisit');
	if(forumVisitsC){
		t='xxx/'+ forumVisitsC+'/';
		t2=t.split('/'+currentForumId+':');
		if(t2.length>1){
			oldPZT=t2[1].split('/');
			if(oldPZT[0]){
				lastPZT=oldPZT[0];
				forumVisitsC=t.replace('/'+currentForumId+':'+lastPZT,'/'+currentForumId+':'+ globalMaxForumPZT);
				forumVisitsC=forumVisitsC.replace('xxx/','');
				setCookie('forumVisit', forumVisitsC,365);
				//console.log('fvisitcookie: fi: '+forumId  + ' replaced:'+lastPZT+' with maxPzt' + globalMaxForumPZT);
			};
		};
	};
}

//merges in new forums with the forumVisit cookie
function forumVisitCookieMerge(forumVisits){

	var forums = document.getElementsByClassName('wfForumItem');
	//console.log('forumVisitCookieMerge');

	// bug with blank cookie content oops
        for(n=0;n< forumVisits.length;n++){
		//console.log(forumVisits[n]+'  l:'+forumVisits[n].length);
		if(forumVisits[n].length==0){
			forumVisits.splice(n,1);
		}
	}

//forumVisits.splice(30,1);
	if(forums.length!=forumVisits.length){

		for(n=0;n<forums.length;n++){
			var id=forums[n].getAttribute('id');
			id=id.replace('wfForumItem','');

			// for each forum check to see if it's in the cookie
			nn=0;

			while(nn<forumVisits.length && forumVisits[nn].split(':')[0]!=id){
				nn++;
			}

			if(nn==forumVisits.length){
				// need to add one
				forumVisits.push(id+':'+ globalMaxForumPZT);
				//console.log('found new forum');
			};
		}

		// now write out the new cookie
		var fVisit='';
		for(n=0;n<forumVisits.length;n++){
			fVisit=fVisit+forumVisits[n]+'/';
		}
		setCookie('forumVisit',fVisit,365);
	}
	forums= null;
}

//function used by the quick reply inline editor to update the db
function quickReplyCallBack(serverData,id){
	document.getElementById('QRE'+id).innerHTML=serverData;  
/*
	document.getElementById('QREX'+id).onkeyup = function(evt) {
		evt = evt || window.event;
		while($(this).outerHeight() < this.scrollHeight + parseFloat($(this).css("borderTopWidth")) + parseFloat($(this).css("borderBottomWidth"))) {
			$(this).height($(this).height()+1);
		};

	};*/

}

//function used by the quick reply inline editor to update the db
function quickReply(itemNumber,forumid,threadid,postid){
	if(document.getElementById('QRED'+itemNumber)){
		document.getElementById('QRED'+itemNumber).innerHTML='';
	}
	var newDiv=document.getElementById('QRE'+itemNumber);
	if(newDiv){
		newDiv.parentNode.removeChild(newDiv);
		return;
	}
	newDiv=document.createElement('div');
	newDiv.id='QRE'+itemNumber;

	addClass(newDiv,'quickReply');
	insertAfter(newDiv,document.getElementById('QR'+itemNumber));
	newDiv=$('QRE'+itemNumber);
	ajaxPage("/?page=wf.edit.quick2&fi="+forumid+'&ti='+threadid+'&pi='+postid+'&id='+ itemNumber, quickReplyCallBack ,itemNumber);

}

/* function to detect if something is visible in the current viewport */
function inViewport (el) {

    var r, html;
    if ( !el || 1 !== el.nodeType ) { return false; }
    html = document.documentElement;
    r = el.getBoundingClientRect();

    return ( !!r 
      && r.bottom >= 0 
      && r.right >= 0 
      && r.top <= html.clientHeight 
      && r.left <= html.clientWidth 
    );
}


function IsImageOk(img) {
    if (!img.complete) {
        return false;
    }
    if (typeof img.naturalWidth !== "undefined" && img.naturalWidth === 0) {
        return false;
    }

    return true;
}

/* function to remove images that are not on display */

function dumpImages(){
	var x = document.getElementsByClassName("wfImg");
	for (var i=0; i<x.length;i++){
		if(IsImageOk(x[i])){
			if(!inViewport(x[i])){
				//x[i].hidden=true;
				//console.log(x[i].src);
				x[i].src = 'data:image/gif;base64,' + 
      'R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs=';
			}else{
				//x[i].hidden=false;
			}
		}
	}
        
}


//pretty crude - if we are less than 800px then we are mobile.
function detectmob() {
	if(window.innerWidth <= 800 /* && window.innerHeight <= 600*/) {
		return true;
	} else {
		return false;
	}
}

function insertAfter(newElement,targetElement) {
	//target is what you want it to go after. Look for this elements parent.
	var parent = targetElement.parentNode;

	//if the parents lastchild is the targetElement...
	if(parent.lastchild == targetElement) {
		//add the newElement after the target element.
		parent.appendChild(newElement);
	} else {
		// else the target has siblings, insert the new element between the target and it's next sibling.
		parent.insertBefore(newElement, targetElement.nextSibling);
	};
}

function setCookie(cname, cvalue, exdays) {
	var d = new Date();
	d.setTime(d.getTime() + (exdays*24*60*60*1000));
	var expires = "expires="+d.toUTCString();
	//console.log('setCookie:'+ cname + '=' + cvalue + '; ' + expires+'; path=/');
        document.cookie = cname + '=;expires=Thu, 01 Jan 1970 00:00:01 GMT; domain=www.watchprosite.com; path=/'; // delete erroneous named cookie
        document.cookie = cname + '=;expires=Thu, 01 Jan 1970 00:00:01 GMT'; // delete erroneous named cookie
	document.cookie = cname + '=' + encodeURIComponent(cvalue) + '; ' + expires+'; domain=.watchprosite.com; path=/';
}

function getCookie(cname) {
	var name = cname + "=";
	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);
		if (c.indexOf(name) == 0){

			var r=c.substring(name.length, c.length);

//alert(r);
r=decodeURIComponent(r);

//alert(r);
 			return r;

		}
	}
	return "";
}

function clearAllCookies(){
	var 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);

		//console.log('cookie:'+c);
		deleteCookie(c);

	}

}
function clearAllCookiesExepts(named){
        var reg=new RegExp(named);
	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);

		if(!reg.test(c)){
		    deleteCookie(c);
                }

	}

}

function isUrlFormat(f,s){
	if(f=='&'){
		return true; // fix this test
	}else if(f=='/'){
			if(/^\/([^\/]+|[^\/]+\/[^\/]+)\/[-]*[0-9.]+\/.*/.test(s)){return true;}else{return false;}
	}else if(f=='-'){
		// cannot be both
			if(/([^-]+)-([^\/]*)\/([^-]+)-([^\/]*)\/.*/.test(s) &&!/^\/([^\/]+|[^\/]+\/[^\/]+)\/[-]*[0-9.]+\/.*/.test(s)){return true;}else{return false;}
	}
}

function deleteCookie(name) {
	document.cookie = name + '=;expires=Thu, 01 Jan 1970 00:00:01 GMT;';
	document.cookie = name + '=;expires=Thu, 01 Jan 1970 00:00:01 GMT; domain=www.watchprosite.com; path=/';
	document.cookie = name + '=;expires=Thu, 01 Jan 1970 00:00:01 GMT; domain=.watchprosite.com; path=/';
	document.cookie = name + '=;expires=Thu, 01 Jan 1970 00:00:01 GMT; domain=www.watchprosite.com';
	document.cookie = name + '=;expires=Thu, 01 Jan 1970 00:00:01 GMT; domain=.watchprosite.com';
};

//uses the contents of the return to cookie to provide a destination for the back button
function goBack(){
	var t=getCookie('pzreturnto');

	if(t){
		// get the content offset record number
		var rn=getHash(t,'rn');
		if(rn.length>0){
			var ut='&';
			//console.log(rn);
			
			if(isUrlFormat('-','/'+t))ut='-';
			if(isUrlFormat('/','/'+t))ut='/';
			
			rn=appendUrlParam('pzt',urlParam('pzt'),ut)+appendUrlParam('wf.query_bLoB_s',(rn-1),ut)+appendUrlParam('gb',1,ut);
			//rn='&pzt='+ urlParam('pzt')+'&wf.query_bLoB_s='+(rn-1)+'&gb=1';
			t=t.replace('#',rn+'#');
		}else{
			// no offset still need to set the pzt
			t=t.split("#")[0]+appendUrlParam('pzt',urlParam('pzt'),'-')+'#'+t.split("#")[1];
		}
		//window.location.href='http://www.watchprosite.com/'+t;
		window.location.href='/'+t;
	}else{
		//window.location.href='http://www.watchprosite.com/page-wf/';
		window.location.href='/page-wf/';
	};
}

function queryStringMinusParameter(parameter){
  var ret='';
  for (var i in urlParams){
   	if(!i.match(parameter) && urlParams[i].length>0){
		if(ret.length==0){
			ret='?';
		}else{
			ret=ret+'&';
		}
		ret=ret+i+'='+urlParams[i];
 	}
	
  }
   
  return ret;

}

function showRecentPosts(){
	//location.href='/?page=wf&q='+ urlParam('q')+'&forumid='+ urlParam('formed')+'&pzt='+ urlParam('pzt')+'';
        location.href=queryStringMinusParameter('wf.query_bLoB_s|gb');
}

//writes the return to cookie
function saveContentOffset(rowNumber){
	var t=getCookie('pzreturnto');
	if(t){
		t=setHash(t,'rn',rowNumber);
		t=setHash(t,'cs',$(window).scrollTop());
		setCookie('pzreturnto',t,365);
	};

}

//stops the propogation of onclick handling up the dom tree.  Used where there is an onclick event inside another.
function clickToUrl(url)
{
	location.href=url;
	if (!e) var e = window.event;
	e.cancelBubble = true;
	if (e.stopPropagation) e.stopPropagation();
}

function encode(string) {
	if(!string)return '';
	string = string.replace(/\r\n/g,"\n");
	var utftext = "";

	for (var n = 0; n < string.length; n++) {

		var c = string.charCodeAt(n);

		if (c < 128) {
			utftext += String.fromCharCode(c);
		}else if((c > 127) && (c < 2048)) {
			utftext += String.fromCharCode((c >> 6) | 192);
			utftext += String.fromCharCode((c & 63) | 128);
		}else {
			utftext += String.fromCharCode((c >> 12) | 224);
			utftext += String.fromCharCode(((c >> 6) & 63) | 128);
			utftext += String.fromCharCode((c & 63) | 128);
		};

	}

	return escape(utftext);
}



function addClass(element, classToAdd) {
	var currentClassValue = element.className;

	if (currentClassValue.indexOf(classToAdd) == -1) {
		if ((currentClassValue == null) || (currentClassValue === "")) {
			element.className = classToAdd;
		} else {
			element.className += " " + classToAdd;
		};
	};
}

function removeClass(element, classToRemove) {
	var currentClassValue = element.className;

	if (currentClassValue == classToRemove) {
		element.className = "";
		return;
	}

	var classValues = currentClassValue.split(" ");
	var filteredList = [];

	for (var i = 0 ; i < classValues.length; i++) {
		if (classToRemove != classValues[i]) {
			filteredList.push(classValues[i]);
		};
	}

	element.className = filteredList.join(" ");
}

function hasClass(element, classToAdd) {
	var currentClassValue = element.className;

	if (currentClassValue.indexOf(classToAdd) == -1) {
		return false;
	}else{
		return true;
	};
}

function Xhr(){ /* returns cross-browser XMLHttpRequest, or null if unable */
    try {
        return new XMLHttpRequest();
    }catch(e){}
    try {
        return new ActiveXObject("Msxml3.XMLHTTP");
    }catch(e){}
    try {
        return new ActiveXObject("Msxml2.XMLHTTP.6.0");
    }catch(e){}
    try {
        return new ActiveXObject("Msxml2.XMLHTTP.3.0");
    }catch(e){}
    try {
        return new ActiveXObject("Msxml2.XMLHTTP");
    }catch(e){}
    try {
        return new ActiveXObject("Microsoft.XMLHTTP");
    }catch(e){}
    return null;
}

function ajaxRequestNextCallback(serverData, serverStatus) {    
	var found=false;
   
	showSelectedForumItem();
	// document.getElementById('waterfall').innerHTML=serverData;
	items= serverData.split("<!--split-->");
	if(items.length>0){
		for (var n = 0; n < items.length-1; n++) { // there is a trailing split

			var iDiv = document.createElement('div');
			if(itemsLoaded==0 && n==0){
				iDiv.setAttribute('data-span', '2');
				items[n]=items[n].replace('/post/','/scaled/');
			}

			// tell it not to load anymore if we get not found
			if(items[n].indexOf('pzZeroResults')>0 ){
				found=true;
				iDiv.setAttribute('data-span', 'all');
				iDiv.setAttribute('data-float', 'left');
				iDiv.setAttribute('style', 'background:none;box-shadow:none;');

			}

			iDiv.innerHTML=items[n];
			document.getElementById('waterfall').appendChild(iDiv);
			//console.log(items[n]);

		}

		itemsLoaded=itemsLoaded+ itemsFetchCount;
		//itemsFetchCount = itemsFetchCount + items.length-1;

		if(!found)loading = false; // reset value of loading once content loaded
$('#waterfall').waterfall('reflow');
//console.log('reflow');
	};  
	
}



function ajaxRequestNext(page,freeText) {
	var AJAX =Xhr();
                  
	if (AJAX==null) {                               
		alert("Your browser doesn't support AJAX.");                                      
		return false;                              
	}
	AJAX.onreadystatechange = function() {                     
		if (AJAX.readyState==4 || AJAX.readyState=="complete") {
			ajaxRequestNextCallback(AJAX.responseText, AJAX.status);            
		}                                                       
	}
	var url='/?page='+page  + '&forumid=' + urlParam('forumid') + '&termId=' +urlParam('termId')+ '&term='+ encode(urlParam('term')) +'&ft='+ encode(freeText) +'&ajax=true'+'&q='+urlParam('q')+'&i='+urlParam('i')+''; 

      //console.log('ajaxRequestNext: '+url);
	AJAX.open("GET", url, true);                                
	AJAX.send(null);                                             
}


function ajaxRequestNewPage(forumId,freeText){
	hideSelectedForumItem();
	currentForumId=forumId;
	showSelectedForumItem();
	itemsLoaded=0;
	loading = true; // reset value of loading once content loaded  

	// dump the contents of the current waterfall

	var divs = document.getElementById("waterfall").getElementsByTagName("div");
	while (divs[0]) {
		divs[0].parentNode.removeChild(divs[0]);
	}

	// ask for a new page

	if(freeText.length>0){
		ajaxRequestNext('wf.ft',freeText);
	}else if(currentForumId=="0"){
		ajaxRequestNext('wf.threads.editorsPicks',freeText);
	}else{
		ajaxRequestNext('wf.threads',freeText);
	}

	if(detectmob()){
		$('#wfForum').addClass('closed');
		$('.page').addClass('closed');
	};

}

/* function to handle an ajaxdata request for a modal box - it's expecting a div with an id of modalContainer and a modal id of myModal */
function ajaxModalShow(serverData){
	// place the html on the page in the special div
	document.getElementById('modalContainer').innerHTML=serverData;
	$('#myModal').modal('show');
}

/* places the results of an ajax call either in the innerHTML of a target dom object or
 * call a user defined function optionally passing parameters.
 * */
function ajaxCallback() {
	var serverData=arguments[0];
	var status= arguments[1];    	// these two are a given
	var obj=null; 
	var parameters=null;

	if(arguments.length>2)obj=arguments[2];  // either a proc or an object
	if(arguments.length>3) parameters =arguments[3];


	// if we were passed a callback function then use it
	if (Object.prototype.toString.call(obj) == "[object Function]") {

		if(parameters){

			obj(serverData, parameters);
		}else{
			obj(serverData);
		};
	}else{

		//console.log('Object.prototype.toString.call(obj):'+Object.prototype.toString.call(obj) );
		// put the results in a div
		if(Object.prototype.toString.call(obj)=='[object String]'){
			document.getElementById(obj).innerHTML=serverData;
		}else{
			obj.innerHTML=serverData;
		}
	};   
}



/* can be called with a variable number of params.
 * 
 * either:  
 *     	ajaxPage(url,userSpecifiedCallbackfuntion | domObject{as an object or the string representing the id})  - the domObjects innerHTML will be set to the result of an ajax call
 * 
 *   or
 *   	ajaxPage(url,userSpoecifiedCallbackfuntion,parameterObject) - as above exept the parameter object is passed to the callbackFunction
 *   
 * */
function ajaxPage(){
	/*
	 * for (var i = 0; i < arguments.length; i++) { alert(arguments[i]); }
	 */
	var page=arguments[0];
	var targetId=arguments[1];
	var params=null;
	if(arguments.length==3)params=arguments[2];
	var AJAX = Xhr();
              
	if (AJAX==null) {                               
		alert("Your browser doesn't support AJAX.");                                      
		return false;                                 
	}
	AJAX.onreadystatechange = function() {                     
		if (AJAX.readyState==4 || AJAX.readyState=="complete") {
			if(!params){
				ajaxCallback(AJAX.responseText, AJAX.status,targetId);
			}else if(params){
				// deal with an extra parameter to the function passed as target
				// id
				ajaxCallback(AJAX.responseText, AJAX.status,targetId,params);
			}            
		}                                                       
	}

	//console.log(page);

	//AJAX.open("POST","/",true);
	//AJAX.setRequestHeader("Content-type","application/x-www-form-urlencoded");
	//AJAX.send(page);


	AJAX.open("GET", page, true);                                
	AJAX.send(null);     
}

function ajaxPageUsingPost(){
	/*
	 * for (var i = 0; i < arguments.length; i++) { alert(arguments[i]); }
	 */
	var page=arguments[0];
	var targetId=arguments[1];
	var params=null;
	if(arguments.length==3)params=arguments[2];
	var AJAX = Xhr();
                                
	if (AJAX==null) {                               
		alert("Your browser doesn't support AJAX.");                                      
		return false;                                 
	}
	AJAX.onreadystatechange = function() {                     
		if (AJAX.readyState==4 || AJAX.readyState=="complete") {
			if(!params){
//console.log("status:"+AJAX.status);
//console.log("response:"+AJAX.responseText);

				ajaxCallback(AJAX.responseText, AJAX.status,targetId);
			}else if(params){
				// deal with an extra parameter to the function passed as target
				// id
				ajaxCallback(AJAX.responseText, AJAX.status,targetId,params);
			}            
		}                                                       
	}



	AJAX.open("POST","https://www.watchprosite.com/",true);
	AJAX.setRequestHeader("Content-type","application/x-www-form-urlencoded");
	AJAX.send(page);

        //console.log("https://www.watchprosite.com/");
        //console.log('ajaxPageUsingPost:',page);
	//AJAX.open("GET", page, true);                                
	//AJAX.send(null);     
}



// legacy ajax call support
function ajaxRequest(url,id){
  document.getElementById(id).innerHTML="";
  url='/?page='+url;
  ajaxPage(url,id);
}

function  showSelectedForumItem(){
	var div=document.getElementById('wfForumItem'+ urlParam('forumid', urlParam('fi','-1')));
	if(div){
		addClass(div,"wfForumItemSelected");
	};
}

function  hideSelectedForumItem(){
	var div=document.getElementById('wfForumItem'+ urlParam('forumid','-1'));
	if(div){
		removeClass(div,"wfForumItemSelected");
	};
}

//set the value of a has string. Hashformat url#param:value-param:value
function setHash(s,h,v){
	var items= s.split("#");
	if(items.length>1){
		s=items[0];
		var found=0;
		var newHash='';
		var hashItems=items[1].split('-');
		for(var n=0;n<hashItems.length;n++){
			var nameValue=hashItems[n].split(':');
			if(nameValue[0]==h){
				nameValue[1]=v;
				found=1;
			}
			if(newHash.length==0){
				newHash='#'+nameValue[0];
			}else{
				newHash=newHash+'-'+nameValue[0];
			}
			newHash=newHash+':'+nameValue[1];
		}
		if(found==0){
			newHash=newHash+'-'+h+':'+v;
		}
		return  s+newHash;
	}else{
		// no hash
		return encodeURI(s+'#'+h+':'+v);
	};
}

//given a hash string return the value of a parameter. Hashformat url#param:value-param:value
function getHash(s,h){
	var items= s.split("#");
	if(items.length>1){
		s=items[0];
		var found=0;
		var hashItems=items[1].split('-');
		for(var n=0;n<hashItems.length;n++){
			var nameValue=hashItems[n].split(':');
			if(nameValue[0]==h){
				return nameValue[1];
			};
		}
		return '';
	}else{
		// no hash
		return '';
	};
}

//return the value of a hash parameter from the current page's href
function hashParameter(param){
	var hash=parent.location.hash;
	if(hash.length==0)return null;
	hash=hash.replace(/#/g,'');
	items=hash.split('-');
	if(items.length==0){
		// 
	}else{
		for(var n=0;n<items.length;n++){

			var hitems=items[n].split(':');
			if(hitems[0]==param)return hitems[1];
		};
	}
	return null;
}

/* auto request next page scrolling */
function loadNextPage(){

	var freeText=urlParam('ft');
	loading= true;
	//dumpImages();
	var page="wf.threads";

	if(urlParams['q']!=''){
		page="wf.query";
	}else if(urlParam('forumid','-1')=="-1"){
		page='wf.query';
	}

	if(freeText.length>0){
		page='wf.ft';
	}


	// loading = false; // reset value of loading once content loaded

	//if we are mobile then do not let them ask for more than 40 items
	if(detectmob() && itemsLoaded>=4000){

		if( !document.getElementById('pztManualNext')){
			
			if(freeText.length>0 || urlParam('q')=='myposts'){
				page='wf'+'&xwf.ft_bLoB_s='+ itemsLoaded +'&searchAll='+urlParam('searchAll');
			}else{
				page='wf'+'&wf.query_bLoB_s='+ itemsLoaded +'&searchAll='+urlParam('searchAll');
			} 
			var href='/?page=' + page +'&pzt='+ urlParam('pzt')+'&gb=1&ft='+ urlParam('ft')+'&q='+ urlParam('q') + '&i=' + urlParam('i') + '&forumid=' + urlParam('forumid');
			
			var iDiv = document.createElement('div');

			iDiv.setAttribute('data-span', 'all');
			iDiv.setAttribute('id', 'pztManualNext');

			iDiv.innerHTML="<a href='"+href+"'>show more posts</a>";
			document.getElementById('waterfall').appendChild(iDiv);
		}


	}else{ 

	if(freeText.length>0){

		page=page+'&pzt='+urlParam('pzt')+'&offset='+ itemsLoaded+'&x'+page+'_bLoB_s='+ itemsLoaded+'&searchAll='+urlParam('searchAll')+'&fts='+urlParam('fts')+'&ftm='+urlParam('ftm')+'&threads='+urlParam('threads')+'&image='+urlParam('image');

	}else{
		page=page+'&pzt='+urlParam('pzt')+'&wf.query_bLoB_s='+ itemsLoaded;

	};

//console.log("loadNextPage: "+page);
		ajaxRequestNext(page,freeText);
	}


}

/* scroll the forums to the correct offset on load*/
function handleScroll(){
    	//console.log('handleScroll');

	//if (handledScroll) return;

	//handledScroll=1;
	//console.log('waterfall:'+document.getElementById('waterfall'));

	//$('#waterfall').waterfall('reflow');
	var fs=hashParameter('fs');
	if(fs>0){
		//console.log('handleScroll scrolled forum list to:'+fs);
		document.getElementById('wfForum').scrollTop=fs;
	};
}




function hideReadThreadsForPZT(){
	var c=getCookie('pztThreadsRead');
	if(c.split('.')[0]==urlParam('pzt')){
		var x = document.getElementById("waterfall").querySelectorAll(".badge.highlighted");  
		for(var i=0;i<x.length;i++){
			var ti=x[i].outerHTML.split('&amp;ti=')[1].split('&')[0];
			if(c.indexOf('.'+ti)!=-1){
				// hide it
				removeClass(x[i],"highlighted");
			}
		}
	}
}



function pztThreadsReadSet(){
	var c=getCookie('pztThreadsRead');
	if(c){
		if(c.split('.')[0]!=urlParam('pzt')){
			c=urlParam('pzt')+'.'+urlParam('ti')+'.';  // new pzt
		}else{
			if(c.indexOf('.'+urlParam('ti'))==-1){
				c=c+'.'+urlParam('ti');
			}
		}
	}else{
		c=urlParam('pzt')+'.'+urlParam('ti')+'.';  // missing cookie
	}
	setCookie('pztThreadsRead',c,1) ;
}
	
function ajaxLoadFirstPage(){
		var freeText=urlParam('ft');
		loading= true;
		var page="wf.threads";

		if(urlParam('q')!=''){
			page="wf.query";
		}else if(urlParam('forumid','-1')=="-1"){
			page='wf.query';
		}
		if(freeText.length>0){
			page='wf.ft';
		}

		if(freeText.length>0 || urlParam('q')=='myposts'){
			ajaxRequestNext(page+'&pzt='+urlParam('pzt')+'&offset='+ itemsLoaded ,freeText);
		}else{
			ajaxRequestNext(page+'&pzt='+urlParam('pzt')+'&'+page+'_bLoB_s='+ itemsLoaded ,freeText);
		};

}

//callback ajax function  the data is formatted n,n = numberOfUnseenItems,lastUnseenDate

function handleUnseenCount(serverData){
	if(serverData){
		var data=serverData.split(',');
		if(data[0]>0){
			//console.log(serverData);
			s=document.getElementById('accountNotify');
			if(s){
				addClass(s,'selected'); //signal that there is new responses
				addClass(document.getElementById('accountNotifyU'),'glyphicon glyphicon-asterisk'); //accountNotifyU
				document.getElementById('accountNotifyU').parentNode.href=document.getElementById('accountNotifyU').parentNode.href+'pzt-'+data[1].trim()+'/';

				//$('#accountNotify').addClass('closed');
			};
		};

		// now the unread pms
		if(data[2]>0){
			if(data[0]==0){	
				s=document.getElementById('accountNotify');
				if(s){
					addClass(s,'selected'); //signal that there is new responses
				};
			};
			addClass(document.getElementById('PMNotifyU'),'glyphicon glyphicon-asterisk'); //PMNotifyU
		};
	};
}

function appendUrlParam(name,value,mode){
	//console.log("n:"+name+" v:"+value+" m:"+mode);
	if(value.length==0) return "";
	if(mode=='-'){
		return name+'-'+encodeURIComponent(value)+'/';
	}else{
		return '&'+name+"="+encodeURIComponent(value);
	}
}



if(document.getElementById('waterfall')){
$(window).scroll(function() {



	if(!document.getElementById('waterfall'))return;

	if (!loading && ($(window).scrollTop() >  $(document).height() - $(window).height() - 500)) {
		loadNextPage();
	};
//	console.log('window scroll function:'+$(window).scrollTop());
});


// function to limit the scrolling to the thing you are hovering over

$('.ScrollableFocus').on('DOMMouseScroll mousewheel', function(ev) {
    var $this = $(this),
        scrollTop = this.scrollTop,
        scrollHeight = this.scrollHeight,
        height = $this.height(),
        delta = (ev.type == 'DOMMouseScroll' ?
            ev.originalEvent.detail * -40 :
            ev.originalEvent.wheelDelta),
        up = delta > 0;

    var prevent = function() {
        ev.stopPropagation();
        ev.preventDefault();
        ev.returnValue = false;
        return false;
    }

    if (!up && -delta > scrollHeight - height - scrollTop) {
        // Scrolling down, but this will take us past the bottom.
        $this.scrollTop(scrollHeight);

        return prevent();
    } else if (up && delta > scrollTop) {
        // Scrolling up, but this will take us past the top.
        $this.scrollTop(0);
        return prevent();
    }
});


//handle the forum open/close
$('.forumToggle').click(function(){
	if(hasClass(document.getElementById('wfForum'),'closed')){
		$('#wfForum').removeClass('closed');
		$('.page').removeClass('closed');
		$('#menuToggle').removeClass('glyphicon-menu-hamburger');		
		$('#menuToggle').addClass('glyphicon-remove');	
		// $('.wfForum-show').attr('hidden', true);
	}else{  
		$('#wfForum').addClass('closed');
		$('.page').addClass('closed');
		// $('.wfForum-show').removeAttr('hidden');
		$('#menuToggle').removeClass('glyphicon-remove');
		$('#menuToggle').addClass('glyphicon-menu-hamburger');

	}
	// this should work as this is how they do it in the example
	$('#waterfall').waterfall('reflow');

})





//if we are on mobile then close the forum menu and resize the page
if(detectmob()){
	$('#wfForum').addClass('closed');
	$('.page').addClass('closed');
	$('#menuToggle').removeClass('glyphicon-remove');
	$('#menuToggle').addClass('glyphicon-menu-hamburger');
}




/*callback =function(){
	//console.log('callback');
	handleScroll();
}*/

/*set a cookie to store the current page if we are on the wf page 
 *  need to convert /// url back to normal as it's just too difficult 
 *  
 * */

if(urlParam('page')=='wf'){
	
	if(isUrlFormat('-',window.location.pathname)||isUrlFormat('/',window.location.pathname)){

		//console.log(urlParams);
		//console.log('q:'+urlParam('q'));
		setCookie('pzreturnto',appendUrlParam('page','wf','-')
				+appendUrlParam('q',urlParam('q'),'-')
				+appendUrlParam('forumid',urlParam('forumid'),'-')
				//+appendUrlParam('pzt',urlParam('pzt'),'-')
				+appendUrlParam('hs',urlParam('hs'),'-')+parent.location.hash,365);
		
	}else{
		setCookie('pzreturnto','?page=wf&q='+ encodeURIComponent(urlParam('q'))+'&qf='+ encodeURIComponent(urlParam('qf'))+'&termId='+urlParam('termId')+'&searchAll='+ encodeURIComponent(urlParam('searchAll'))+'&ft='+urlParam('ft')+'&forumid='+urlParam('forumid')+''+parent.location.hash,365);	
	}
//carl
}

handleScroll();
handleNewForumContent();

showSelectedForumItem();
ajaxPage(window.location.protocol + '//' + window.location.host + '/?page=wf.unseenCount', handleUnseenCount);

/* this is probably redudundant  
$("textarea").keyup(function(e) {
	//console.log('textarea keyup');
	while($(this).outerHeight() < $(this).scrollHeight + parseFloat($(this).css("borderTopWidth")) + parseFloat($(this).css("borderBottomWidth"))) {
		$(this).height($(this).height()+1);
	};
});
*/

if(urlParams['page']=='wf.forumpost'){
  pztThreadsReadSet();
}
if(urlParams['page']=='wf'){
 // auto load next page if this
 if(!document.getElementById('pzNothingFound'))
  loadNextPage();
}


if(urlParam('page')=='wf'){

  hideReadThreadsForPZT();

  // ajaxLoadFirstPage();
}


}


