
// Category / Subcategory expanding list
window.addEvent('domready', function() {

	// Only check once per day irrespective of whether a campaign is set
	if(!Cookie.read('ProtalkMemberCampaign')){
		// If we havent checked today, see if a campaign in running
		var campReq = new Request.JSON({
		   url: '/ajaxHandler.php',
		   data: {
			   Site: 'mkttalk',
			   Method: 'checkForCampaignMessage'
		   },
		   onSuccess: function(response){
			   if(response.id){
				   // If there is a campaign set up see if this user has already been asked
				   if(!Cookie.read(response.cookiename)){
					   // Wait delay number of seconds
					   setTimeout(function(){
						   var size = window.getSize();

						   // Create and show the window
						   var El = new Element('div',{
									   'id': 'campaigndiv',
								   styles: {
									   'opacity' : 0,
									   'z-index' : 299,
									   'left': response.left ? response.left : ( (size.x/2) - (response.width/2)) + 'px',
									   'top': response.top ? response.top : ( (size.y/2) - (response.height/2)) + 'px'
								   }
						   }).inject('content','top');

						   var contents = '';

						   	contents += '<div style="background: url(http://www.marketingservicestalk.com/style/images/popup/shadow.png) no-repeat bottom; width: ' + response.width + 'px; padding: 0 0 7px 0;">';
						   	contents += '<div style="background: #fff url(http://www.marketingservicestalk.com/style/images/popup/background.gif) repeat-x bottom; width: ' + response.width + 'px; border: solid 1px #455560;">';
						   	contents += '<div style="background: #494646; padding: 10px; width: ' + (response.width-20) + 'px; display: inline-block;">';
						   	contents += '<img src="http://www.marketingservicestalk.com/style/images/extra/marketingweek marketplace.gif" alt="Marketingweek Marketplace"  height="30" style="float: left;"/>';
						   	contents += '<a href="javascript: closecampaign();" title="Whoah! Before you go, this isn\'t a survey, but a great way to get more out of Marketingweek Marketplace for FREE">';
						   	contents += '<p style="font-size: 1.2em; color: white; line-height: 1.4em; font-weight: normal; margin: 0; padding: 0; background: url(http://www.marketingservicestalk.com/style/images/popup/close.gif) no-repeat right; margin: 6px 0 0 0; padding: 2px 21px 2px 0; float: right;" class="logo">';
						   	contents += 'Close</p></a>';
						   contents += '</div>';

						   	contents += '<iframe src="' + response.contents + '" style="width: ' + response.width + 'px; height: ' + response.height + 'px; " scrolling="no" id="camiframe" ></iframe>';
						   contents += '</div></div>';
						   //contents += '';

						   $('campaigndiv').makeDraggable();

						   $('campaigndiv').innerHTML = contents;

						   $('camiframe').addEvent('load',function() {
							   $('campaigndiv').setStyle('width',$('camiframe').getSize().x);
							   $('campaigndiv').setStyle('height',$('camiframe').getSize().y);
						   });

						   $('campaigndiv').set('tween',{duration:response.fadetime ? response.fadetime * 1000 : 1000});
						   $('campaigndiv').tween('opacity',1.0);

						   // Write the cookie for this campaign
						   if(response.writecookie == 'yes'){
							   Cookie.write(response.cookiename,'asked',{duration: response.cookieduration, path: '/' });
						   }
					   },response.delay * 1000);
				   }
			   }
		   }
	   }).send();

		// Set the cookie so this is only done once per day
		Cookie.write('ProtalkMemberCampaign','checked',{duration:1, path:'/'});
	}

	var catListAccordian = new Accordion($$('.toggler'), $$('.element'), {
		start:'all-closed',
		opacity: false,
		alwaysHide: true
	});

	
		var webtracker = new WebTracker(30000,'/WebTrackerProxy.php');
	webtracker.run();
		
});

function closecampaign(){

	$('campaigndiv').tween('opacity',0).chain(function(){
		$('campaigndiv').dispose()
	})
}


var curTab = '1';

function openTab(tab){
	$('tabContent'+curTab).setStyle('display','none');
	$('tabContent'+tab).setStyle('display','block');

	$('tab'+curTab).removeClass('active');
	$('tab'+tab).addClass('active');
	curTab = tab;
}


var findTab = '1';

function openFindTab(tabs){
	$('findTab'+findTab).setStyle('display','none');
	$('findTab'+tabs).setStyle('display','block');

	$('tabs'+findTab).removeClass('active');
	$('tabs'+tabs).addClass('active');
	findTab = tabs;
}



/**
 * 	WebTracker is a light-weight, custom Javascript class that makes use of the XMLHttpRequest object
 * 	in order to pass limited information back to the server.
 * 
 * 	This is useful for tracking the browsing patterns of annonymous users in terms of our own
 * 	site's content - specifically, the click pattern and bounce rate.
 *
 *  Modified to ensure that the IP address is always kept server side.
 *
 *  Additionally, removed code that kept updating the server - as currently no longer 
 *  monitoring duration.
 * 
 *  @author Adrian Latham <adrian.latham@centaur.co.uk>
 *  @version 0.0.3
 *
 */
function WebTracker(freq, url) {

	// instance variables

	// set by server following first Ajax call
	this.cookieId = null;
	// url requested
	this.page = null;
	// referrer url, if applicable
	this.referrer = null;
	// xmlHttpRequest object
	this.xhr = null;
	// frequency with which to contact server
	//this.freq = 10000;
	// sets the server url to be called
	this.url = null;
	// reporting browser type
	this.browser = null;

	/*
	 * this will hold the randomly generated string.
	 * although not strictly required as an instance variable,
	 * it is used during unit testing
	 */
	this.gibberish = null;

	// this is a bit like a constructor method here, or instance code blocks in Java,
	// ideal for setting up instance vars based on conditional statements

	// if passed, set it...
	if (typeof(freq) != "undefined") {
		this.freq = parseInt("" + freq + "000");
	}

	// if passed, set it...
	if (typeof(url) != "undefined") {
		this.url = url;
	}



	/**
	 *
	 * This method sets the ball rolling.  It controls the flow of the application -
	 * by setting instance variables, getting an AJAX call in immediately, then
	 * calling the AJAX method periodically
	 *
	 * @return void
	 *
	 */
	this.run = function()
	{
		// let's set up the instance vars...
		this.setUp();
		// no messing about, get the first AJAX call in
		if (!this.track()) {
			//document.write("Oops, we've got a problem!");
		}
		// now we've made contact, let's repeat every x secs
		// due to quirks in Javascript's object based nature
		// and setInteval's behaviour, we need to create an
		// annonymous function that accepts a reference of this that
		// returns another annonymous function that calls the
		// instances track method on the passed instance!
		// not logging duration at this time, so commented this out
		//setInterval((function(self){ return function() { self.track()}})(this), this.freq);
	}


	/**
	 *  This method will set the object's freq property.  It converts
	 *  seconds to milliseconds and performs a type cast
	 *
	 *  @param integer freq
	 *  @return boolean
	 */
	this.setFreq = function (freq)
	{
		// convert to integer
		freq = parseInt(freq);
		if (freq <= 0) {
			return false;
		}
		var millis = freq * 1000;
		this.freq = millis;
		return this.freq == millis;
	}


	/**
	 *
	 * This method sets up the object's instance properties
	 *
	 */
	this.setUp = function ()
	{
		this.cookieId = this.getCookie("cookieId");
		this.page = (this.page == null) ? window.location.href : this.page;
		this.referrer = (this.referrer == null) ? document.referrer : "";
		this.browser = navigator.appName;
	}



	/**
	 * Sets the values of the class properties, if null, then calls httpRequest method
	 * to do the Ajax part
	 * @return boolean
	 */
	this.track = function ()
	{
		// let's url encode the values and send off to server...
		return this.httpRequest(this.buildUpQueryString(this.cookieId, this.page, this.referrer, this.browser));
	}


	/**
	 * Builds up query string for XMLHttpRequest post later
	 * @param string cookie
	 * @param string page
	 * @param string ip
	 * @return string
	 */
	this.buildUpQueryString = function (cookieId, page,referrer, browser)
	{
		return "webtracker=true&cookieId=" + encodeURIComponent(cookieId)
		+ "&page=" + encodeURIComponent(page)
		+ "&referrer=" + encodeURIComponent(referrer) + "&browser=" + encodeURIComponent(browser)
		+ "&gibberish=" + encodeURIComponent(this.getRandomString(8));
	}


	/**
	 * This will return a random string based on size parameter
	 * @param integer size
	 * @return string
	 */
	this.getRandomString = function (size)
	{
		if (size < 0) {
			size = 10;
		}
		// let's also append a random string to help avoid any browsers caching the query string for AJAX calls
		var randomString = "";
		var chars = new Array ("a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","1","2","3","4","5","6","7","8","9");
		for (var i = 0; i < size; i++) {
			randomString += chars[Math.floor(Math.random()*chars.length)];
		}
		// used for unit testing
		this.gibberish = randomString;
		return randomString;
	}


	/**
	 *
	 * This method is the XMLHttpRequest callback.  It looks at the state of the object
	 * to determine what to do next.  In this case, it isn't really being used
	 * interactively - except to set a cookie, if required
	 *
	 */
	this.handleResponse = function ()
	{
		if (this.xhr.readyState == 4) {
			if (this.xhr.status == 200) {
				// if new visitor, it will include cookieId
				var reply = this.xhr.responseText;
				// cookieId is md5 hash 32 chars long
				// anything else is not a valid cookieId
				if (document.getElementById("debug")) {
					document.getElementById("debug").innerHTML += "<br \/> length: " + reply.length;
				}
				if (reply.length == 32) {
					// let's use it to set the cookieId
					this.setCookie("cookieId", reply);
				}
				if (document.getElementById("debug")) {
					document.getElementById("debug").innerHTML += "<br \/>" + reply;
				}
			}
		}
	}


	/**
	 * Makes the AJAX call
	 * @param string queryString
	 * @return boolean
	 */
	this.httpRequest = function (queryString)
	{
		// W3C browsers
		if (window.XMLHttpRequest) {
			this.xhr = new XMLHttpRequest();
		// IE browsers
		} else if (window.ActiveXObject) {
			this.xhr = new ActiveXObject("Microsoft.XMLHTTP");
		}
		if (this.xhr) {
			// if set, let's post data
			// due to quirks in Javascript's object based nature need to create
			// annonymous function that accepts a reference of this that
			// returns another annonymouse function that calls the
			// instances track method on the passed instance!
			this.xhr.onreadystatechange = (function (self) { return function() { self.handleResponse(); }}) (this);
			this.xhr.open("POST",this.url, true);
			this.xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
			this.xhr.send(queryString);
			return true;
		}
		return false;
	}



	/**
	 * Returns the value for a given cookie name or empty string
	 * @param string name
	 * @return string
	 */
	this.getCookie = function (name)
	{
		// okay, let's return any cookieId if already set.  This is necessary,
		// of example, where cookies are disabled.
		if (this.cookieId != null && this.cookieId.length > 0) {
			return this.cookieId;
		}
		// if not already set, maybe it is as a cookie...
		if (document.cookie.length > 0) {
			start = document.cookie.indexOf(name + "=");
			if (start != -1) {
				start = start + name.length + 1;
				end = document.cookie.indexOf(";", start);
				if (end == -1) {
					end = document.cookie.length;
				}
				return unescape(document.cookie.substring(start, end));
			} else {
				return "";
			}
		} else {
			return "";
		}
	}


	/**
	 * Sets the cookie name and value pair, also sets expiry date 10 years ahead
	 * @param string name
	 * @param string value
	 * @return boolean
	 */
	this.setCookie = function (name, value)
	{
		var expiryDate = new Date();
		// setting the expiry date 10 years ahead...not possible to set indefinately
		expiryDate.setDate(expiryDate.getDate() + 3650);
		document.cookie = name + "=" + escape(value) + ";expires=" + expiryDate.toGMTString();
		// ensure set here too
		this.cookieId = value;
		return this.getCookie(name) == value;
	}

} // class


//---------------- set the sc account variables -----------------//
var s_account="centaurmarketingservicestalk"
var theLinkInternalFilters = "javascript:,marketingservicestalk.com"


//------------------- tynt copy and paste code ------------------//


if(document.location.protocol=='http:'){
 var Tynt=Tynt||[];Tynt.push('cA_HFmQRar3718adbi-bpO');
 (function(){var s=document.createElement('script');s.async="async";s.type="text/javascript";s.src='http://tcr.tynt.com/ti.js';var h=document.getElementsByTagName('script')[0];h.parentNode.insertBefore(s,h);})();
}


