var dateObj=new Date();
var now=dateObj.getTime();

var fadedOpacity = 85;
var gradient = 10;
var tick = 25;
var intervalID;

var twitterVisible=0;

var boxWidth = 550;

var popupDelay = 3; //seconds

var doingSomething = 0;

window.onload=initialise;

display = 0;
dslp = 0;
debug_text = "";

prepare();

function prepare() {
	if (cookieCheck() == true) {
		lastPopup= getCookie("psbookLastPopup_facebookTwitter");
		
		if (lastPopup == "") { //no popup before
			debug_text = debug_text + "none before / ";
			dslp = -1;
			
			//alert('no previous cookie');
			display = 1;

		} else {
			dslp = daysSince(lastPopup);
			//alert('Days since previous cookie = ' + daysSince(lastPopup));
			if (daysSince(lastPopup) > (7 * 5)) {
				now2=dateObj.getTime();
				display = 1;
			} else {
				//debug("Last cookie "+ daysSince(lastPopup) +" ago. No.");
			}
		}
	} else {
		dslp = "failed cookie test";
	}
}

function isGooglebot() {
	var agent = navigator.userAgent;
	if ((agent.indexOf("Googlebot") > -1) || (agent.indexOf("Google Web Preview") > -1)) return 1;
	else return 0;
}

function initialise() {

	debug("Your last popup displayed " + dslp + " days ago."); //  + navigator.userAgent);

	// The follow button in the sidebar
	//twttr.anywhere(function (T) {
	//	T('#follow-psbook-sidebar').followButton("psbook");
	//});

	if (display && !isGooglebot()) {
		createFadeBlock();
		createPopupBox();

		var dateObj2=new Date();
		var now2=dateObj2.getTime();

		if ((now2 - now) > (popupDelay * 1000)) {
			popup();
		} else {
			setTimeout("popup()",(popupDelay * 1000) - (now2 - now));
		}
	}
}

function cookieCheck() {
	setCookieAdvanced("psbookTestCookie","CANHAZCOOKIES",365,"/");

	t = getCookie('psbookTestCookie');
	
	if (t == 'CANHAZCOOKIES') {
		//alert('passed check');
		return true;
	} else {
		//alert('failed check');
		return false;
	}
}

function daysSince(prevDate) {
	var minutes=1000*60;
	var hours=minutes*60;
	var days=hours*24;

	days2 = now/days;
	days1 = prevDate / days;

	return days2 - days1;
}

function popup() {
	setCookieAdvanced("psbookLastPopup_facebookTwitter",now,365,"/");
	turnOffFlash();
	
	if (doingSomething == 1) return;
	else doingSomething = 1;
	
	fb = document.getElementById('fadeBlock');
	box = document.getElementById('popupBox');
	
	setOpacity(fb,0);	
	fb.style.display='block';
	intervalID = setInterval("fadeIn(fb,fadedOpacity,'fadeIn(box,100,null)')",tick);

	if (BrowserDetect.browser == 'Explorer') 
		boxWidth = boxWidth + 40;
	
	setOpacity(box,0);
	box.style.width = boxWidth + 'px';
	
	if (BrowserDetect.browser == 'Explorer') {
		box.style.left= Math.round((document.body.clientWidth - boxWidth) / 2) + 'px';
		//box.style.top= Math.round((document.body.clientHeight - box.style.height) / 2) + 'px';
	} else {
		box.style.left= Math.round((window.innerWidth - boxWidth) / 2) + 'px';
		//box.style.top= Math.round((window.innerHeight - box.style.height) / 2) + 'px';
	}
	
	box.style.top = '25px';
	box.style.display='';
	
	if ((BrowserDetect.browser == 'Explorer') || (BrowserDetect.browser == 'Firefox'))
		showTwitterButton();
}

function unpopup() {
	if (doingSomething == 1) return;
	else doingSomething = 1;	
	
	fb = document.getElementById('fadeBlock');
	box = document.getElementById('popupBox');
	
	intervalID = setInterval("fadeOut(box,'fadeOut(fb,null)')",tick);
}


function fadeIn(obj,target,doNext) {
	
	currentOpacity = getOpacity(obj);
	if ((currentOpacity + gradient) >= target) {
		setOpacity(obj,target);
		currentOpacity = target;
		clearInterval(intervalID);
		
		if (doNext != null) intervalID = setInterval(doNext,tick);
		else doingSomething = 0;
		
	} else {
		setOpacity(obj,currentOpacity + gradient);
		currentOpacity = currentOpacity + gradient;
	}
}

function fadeOut(obj,doNext) {
	currentOpacity = getOpacity(obj);
	
	if ((currentOpacity - gradient) < 0) {
		setOpacity(obj,0);
		currentOpacity = 0;
		obj.style.display='none';
		clearInterval(intervalID);
		
		if (doNext != null) intervalID = setInterval(doNext,tick);
		else {
			turnOnFlash();
			doingSomething = 0;
		}
		
	} else {
		setOpacity(obj,currentOpacity - gradient);
		currentOpacity = currentOpacity - gradient;
	}
}

function turnOffFlash() {
	objects = document.getElementsByTagName('object');
	for (i=0;i<  objects.length;i++) {
		objects[i].style.display='none';
	}
}

function turnOnFlash() {
	objects = document.getElementsByTagName('object');
	for (i=0;i<  objects.length;i++) {
		objects[i].style.display='inline';
	}
}

function createFadeBlock() {
	bodyElement = document.getElementsByTagName('body')[0];
	
	fadeBlockElement = document.createElement('div');
	fadeBlockElement.setAttribute('id','fadeBlock');
	
	//fadeBlockElement.setAttribute('onClick','unpopup();');
	
	addListener(fadeBlockElement, 'click', unpopup, false);
	
	fadeBlockElement.style.display = 'none';
	setOpacity(fadeBlockElement,0);

	bodyElement.appendChild(fadeBlockElement);
}

function createPopupBox() {
	bodyElement = document.getElementsByTagName('body')[0];
	popupElement = document.createElement('div');
	popupElement.setAttribute('id','popupBox');
	
	popupElement.innerHTML = '<div id="popupHeader">Get your left-wing gossip fix!</div><div id="popupIntro">Get the latest news and gossip from the blog the New Statesman called <span style="font-weight:bold;">&ldquo;a must-read site for left and right alike&rdquo;</span> by joining our <span style="font-weight:bold;">11,000+ followers</span> on <a href="http://www.facebook.com/PoliticalScrapbook" target="_blank">Facebook</a> and <a href="http://twitter.com/psbook" target="_blank">Twitter</a>:</div><div id="popupCol1"><div><img src="http://politicalscrapbook.net/wp-content/plugins/psbook-popups/popup_facebook.png" /></div><iframe src="http://www.facebook.com/plugins/likebox.php?id=148379514217&amp;width=292&amp;connections=0&amp;stream=false&amp;header=true&amp;height=62" scrolling="no" frameborder="0" style="border:none;overflow:hidden;width:240px;height:62px;" allowTransparency="true"></iframe></div><div style="float:right;clear:"><img src="http://politicalscrapbook.net/wp-content/plugins/psbook-popups/popup_twitter.png" /></div><div id="popupCol2"><a href="http://twitter.com/psbook" target="_blank"><img src="http://politicalscrapbook.net/wp-content/plugins/psbook-popups/twitter_static_button.png"/></a></div><div id="popupClose" onclick="unpopup();"><img src="http://www.huddletogether.com/projects/lightbox2/images/closelabel.gif" /></div>';
	
	popupElement.style.display = 'none';
	setOpacity(popupElement,0);

	bodyElement.appendChild(popupElement);
	
	if ((BrowserDetect.browser != 'Explorer') && (BrowserDetect.browser != 'Firefox')) {
		showTwitterButton();
	}
}


//opacity between 0 and 100
function setOpacity(obj,value) {
	obj.style.opacity = value/100;
	obj.style.filter = 'alpha(opacity=' + value + ')';
}

function getOpacity(obj) {
	return obj.style.opacity * 100;
}

function showTwitterButton() {
	if (twitterVisible == 0) {
		twttr.anywhere(function (T) {
			T('#follow-psbook').followButton("psbook");
		});
		twitterVisible = 1;
	}
}

//Cross-browser implementation of element.addEventListener()
function addListener(element, type, expression, bubbling)
{
	bubbling = bubbling || false;
	
	if(window.addEventListener)	{ // Standard
		element.addEventListener(type, expression, bubbling);
		return true;
	} else if(window.attachEvent) { // IE
		element.attachEvent('on' + type, expression);
		return true;
	} else return false;
}

function debug(text) {
	infoSection = document.getElementById('siteinfo');
	infoSection.innerHTML = infoSection.innerHTML + ' ' + text;
}

function setCookie(c_name,value,expiredays) {
	var exdate=new Date();
	exdate.setDate(exdate.getDate()+expiredays);
	document.cookie=c_name+ "=" +escape(value) + ((expiredays==null) ? "" : ";expires="+exdate.toUTCString());
}

function getCookie(c_name) {
	if (document.cookie.length>0) {
		c_start=document.cookie.indexOf(c_name + "=");
		if (c_start!=-1) {
			c_start=c_start + c_name.length+1;
			c_end=document.cookie.indexOf(";",c_start);
			if (c_end==-1) c_end=document.cookie.length;
				return unescape(document.cookie.substring(c_start,c_end));
		}
	}
	return "";
}


function setCookieAdvanced( name, value, expires, path, domain, secure )
{
// set time, it's in milliseconds
var today = new Date();
today.setTime( today.getTime() );

/*
if the expires variable is set, make the correct
expires time, the current script below will set
it for x number of days, to make it for hours,
delete * 24, for minutes, delete * 60 * 24
*/
if ( expires )
{
expires = expires * 1000 * 60 * 60 * 24;
}
var expires_date = new Date( today.getTime() + (expires) );

document.cookie = name + "=" +escape( value ) +
( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) +
( ( path ) ? ";path=" + path : "" ) +
( ( domain ) ? ";domain=" + domain : "" ) +
( ( secure ) ? ";secure" : "" );
}

var BrowserDetect = {
		init: function () {
			this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
			this.version = this.searchVersion(navigator.userAgent)
				|| this.searchVersion(navigator.appVersion)
				|| "an unknown version";
			this.OS = this.searchString(this.dataOS) || "an unknown OS";
		},
		searchString: function (data) {
			for (var i=0;i<data.length;i++)	{
				var dataString = data[i].string;
				var dataProp = data[i].prop;
				this.versionSearchString = data[i].versionSearch || data[i].identity;
				if (dataString) {
					if (dataString.indexOf(data[i].subString) != -1)
						return data[i].identity;
				}
				else if (dataProp)
					return data[i].identity;
			}
		},
		searchVersion: function (dataString) {
			var index = dataString.indexOf(this.versionSearchString);
			if (index == -1) return;
			return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
		},
		dataBrowser: [
			{
				string: navigator.userAgent,
				subString: "Chrome",
				identity: "Chrome"
			},
			{ 	string: navigator.userAgent,
				subString: "OmniWeb",
				versionSearch: "OmniWeb/",
				identity: "OmniWeb"
			},
			{
				string: navigator.vendor,
				subString: "Apple",
				identity: "Safari",
				versionSearch: "Version"
			},
			{
				prop: window.opera,
				identity: "Opera"
			},
			{
				string: navigator.vendor,
				subString: "iCab",
				identity: "iCab"
			},
			{
				string: navigator.vendor,
				subString: "KDE",
				identity: "Konqueror"
			},
			{
				string: navigator.userAgent,
				subString: "Firefox",
				identity: "Firefox"
			},
			{
				string: navigator.vendor,
				subString: "Camino",
				identity: "Camino"
			},
			{		// for newer Netscapes (6+)
				string: navigator.userAgent,
				subString: "Netscape",
				identity: "Netscape"
			},
			{
				string: navigator.userAgent,
				subString: "MSIE",
				identity: "Explorer",
				versionSearch: "MSIE"
			},
			{
				string: navigator.userAgent,
				subString: "Gecko",
				identity: "Mozilla",
				versionSearch: "rv"
			},
			{ 		// for older Netscapes (4-)
				string: navigator.userAgent,
				subString: "Mozilla",
				identity: "Netscape",
				versionSearch: "Mozilla"
			}
		],
		dataOS : [
			{
				string: navigator.platform,
				subString: "Win",
				identity: "Windows"
			},
			{
				string: navigator.platform,
				subString: "Mac",
				identity: "Mac"
			},
			{
				   string: navigator.userAgent,
				   subString: "iPhone",
				   identity: "iPhone/iPod"
		    },
			{
				string: navigator.platform,
				subString: "Linux",
				identity: "Linux"
			}
		]

	};
	BrowserDetect.init();

