/*
cbb function by Roger Johansson, http://www.456bereastreet.com/
*/
var cbb = {
	init : function() {
	// Check that the browser supports the DOM methods used
		if (!document.getElementById || !document.createElement || !document.appendChild) return false;
		var oElement, oOuter, oI1, oI2, tempId;
	// Find all elements with a class name of cbb
		var arrElements = document.getElementsByTagName('*');
		var oRegExp = new RegExp("(^|\\s)cbb(\\s|$)");
		for (var i=0; i<arrElements.length; i++) {
	// Save the original outer element for later
			oElement = arrElements[i];
			if (oRegExp.test(oElement.className)) {
	// 	Create a new element and give it the original element's class name(s) while replacing 'cbb' with 'cb'
				oOuter = document.createElement('div');
				oOuter.className = oElement.className.replace(oRegExp, '$1cb$2');
	// Give the new div the original element's id if it has one
				if (oElement.getAttribute("id")) {
					tempId = oElement.id;
					oElement.removeAttribute('id');
					oOuter.setAttribute('id', '');
					oOuter.id = tempId;
				}
	// Change the original element's class name and replace it with the new div
				oElement.className = 'i3';
				oElement.parentNode.replaceChild(oOuter, oElement);
	// Create two new div elements and insert them into the outermost div
				oI1 = document.createElement('div');
				oI1.className = 'i1';
				oOuter.appendChild(oI1);
				oI2 = document.createElement('div');
				oI2.className = 'i2';
				oI1.appendChild(oI2);
	// Insert the original element
				oI2.appendChild(oElement);
	// Insert the top and bottom divs
				cbb.insertTop(oOuter);
				cbb.insertBottom(oOuter);
			}
		}
	},
	insertTop : function(obj) {
		var oOuter, oInner;
	// Create the two div elements needed for the top of the box
		oOuter=document.createElement("div");
		oOuter.className="bt"; // The outer div needs a class name
	    oInner=document.createElement("div");
	    oOuter.appendChild(oInner);
		obj.insertBefore(oOuter,obj.firstChild);
	},
	insertBottom : function(obj) {
		var oOuter, oInner;
	// Create the two div elements needed for the bottom of the box
		oOuter=document.createElement("div");
		oOuter.className="bb"; // The outer div needs a class name
	    oInner=document.createElement("div");
	    oOuter.appendChild(oInner);
		obj.appendChild(oOuter);
	},
	// addEvent function from http://www.quirksmode.org/blog/archives/2005/10/_and_the_winner_1.html
	addEvent : function(obj, type, fn) {
		if (obj.addEventListener)
			obj.addEventListener(type, fn, false);
		else if (obj.attachEvent) {
			obj["e"+type+fn] = fn;
			obj[type+fn] = function() { obj["e"+type+fn]( window.event ); }
			obj.attachEvent("on"+type, obj[type+fn]);
		}
	}
};
/**
 * Cookie plugin
 *
 * Copyright (c) 2006 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */
jQuery.cookie=function(name,value,options){if(typeof value!='undefined'){options=options||{};if(value===null){value='';options.expires=-1}var expires='';if(options.expires&&(typeof options.expires=='number'||options.expires.toUTCString)){var date;if(typeof options.expires=='number'){date=new Date();date.setTime(date.getTime()+(options.expires*24*60*60*1000))}else{date=options.expires}expires='; expires='+date.toUTCString()}var path=options.path?'; path='+(options.path):'';var domain=options.domain?'; domain='+(options.domain):'';var secure=options.secure?'; secure':'';document.cookie=[name,'=',encodeURIComponent(value),expires,path,domain,secure].join('')}else{var cookieValue=null;if(document.cookie&&document.cookie!=''){var cookies=document.cookie.split(';');for(var i=0;i<cookies.length;i++){var cookie=jQuery.trim(cookies[i]);if(cookie.substring(0,name.length+1)==(name+'=')){cookieValue=decodeURIComponent(cookie.substring(name.length+1));break}}}return cookieValue}};

var countSeconds = function(args){
	this.initialize(args);
}
var seconds;
countSeconds.prototype = {
	initialize: function(args){
		if($.cookie('drammenSurveyClosed') == 'Yes')
			return false;
		seconds = this.getSeconds(args);
		this.timer;
		timer = setInterval(this.incrementSeconds, 1000);
		
	},
	
	getSeconds: function(args){
		if($.cookie('drmkSurveyTimer')){
			return $.cookie('drmkSurveyTimer');
		} else {
			return 0;
		}
	},
	
	incrementSeconds: function(){
//		alert(this.getSeconds());
		if(seconds < 60)
			seconds++;
//		$('div#testSurvey').append(seconds);
		if(seconds>=60){
			if($('#dialog').length)  {  showPopup(); }
			clearInterval(this.timer);
			return false;
		}
	}
/*	
	saveSeconds: function(){
		alert('no');
		var expDate = new Date();
		expDate.setTime(expDate.getTime() + 31536000000);
		$.cookie('drmkSurveyTimer', seconds, { expires: expDate });
		alert(seconds);
	}
*/
};

var drmkSurvey;
var ModalWindow = function(args) {
	this.initialize(args);
}

ModalWindow.prototype = {
	initialize: function(args) {
		if(args.autoLaunch && args.secondsBetween && $.cookie(args.cookieName) != 'Yes' && $(args.window).length){
			if(navigator.cookieEnabled)
				this.displayWindow(args);
		} else if(args.autoLaunch && !args.secondsBetween) {
			this.displayWindow(args);
		} else if(args.selector.trigger) {
			var self = this;
			$(args.selector.trigger).click(function () {
				self.displayWindow(args);
			});
		} else {
			
		}
	},
	
	displayWindow : function (args) {
		var self = this;
		cbb.init();
		this.maskWindow(args);
		this.positionWindow(args.selector.window);
		$(args.selector.window).fadeIn(1000); 
		
		//if element with class close is clicked
		$(args.selector.close).unbind("click").click(function () {
			self.closeWindow(args, this);
		});	
	},
	
	displaySecondWindow : function (args) {
		var self = this;
		this.maskWindow(args);
		this.positionWindow(args.selector.secondWindow);
		$(args.selector.secondWindow).fadeIn(1000); 
		
		//if element with class close is clicked
		$(args.selector.close).unbind("click").click(function () {
			self.closeWindow(args, this, args.selector.secondWindow);
		});	
	},
	
	maskWindow : function (args) {
		$(args.selector.mask).css({'width':$(document).width(),'height':$(document).height()});
		$(args.selector.mask).show();
		$(args.selector.mask).fadeTo("slow",0.85);	
	},
	
	positionWindow : function (surveyWindow) {              
		//Set the popup window to center
		$(surveyWindow).css('top',  $(window).height()/2-$(surveyWindow).height()/2);
		$(surveyWindow).css('left', $(window).width()/2-$(surveyWindow).width()/2);
	},
	
	closeWindow : function (args, el, secondWindow) {
		if(secondWindow){
			$(secondWindow).fadeOut('fast');
			$(args.selector.mask).fadeOut('slow');
			return false;
		}
		var self = this;
		var expDate = new Date();
		if($(el).hasClass(args.selector.wait)){
			expDate.setTime(expDate.getTime() + args.waitSecondsBetween);
		} else {
			expDate.setTime(expDate.getTime() + args.secondsBetween);
		}
		$.cookie(args.cookieName, 'Yes', { expires: expDate, path: '/' });
		$(args.selector.mask).fadeOut('slow');
		$(args.selector.window).fadeOut('fast');
		
		
		if($(el).hasClass(args.selector.surveyLink)){
			drmkSurvey = self.createWindow(drmkSurvey, args);
			this.displaySecondWindow(args);
//			win2 = window.open(args.survey.link, 'objWindow', 'status=off,toolbar=off,location=off,menubar=off,directories=off,resizable=on,scrollbars=on');		
//			win2.blur();
//			if (window.focus) window.focus();
		}
		return false;
	},
	
	/* Drammen spesific */
	
	createWindow : function (objWindow, args) {
		objWindow = window.open('http://www.analyzethis.no/v3/drammen/Login.aspx?username=zu8l6ix4vrU%3d&password=zu8l6ix4vrU%3d', '', '');
		return objWindow;
	}
	
	
}

$(document).ready(function() {	
/*	var surveyTimer = new countSeconds({
		cookieName: 'drmkSurveyTime',
		cookieTime: 31536000000,
		timeLimit: 60 // seconds
	});*/
//	$('div#testSurvey').append($.cookie('drammenSurveyClosed'));
//	$('div#testSurvey').append($.cookie('drmkSurveyTimer') + '<br />');
});

var showPopup = function() {
	
	var surveyWindow = new ModalWindow({
		selector: {
			mask: 'div.mask',
			close: '.close',
			surveyLink: '.survey-link',
			wait: '.survey-later',
			window: '#dialog',
			secondWindow: '#dialog-step2'
		},
		secondsBetween: 31536000000, // 1000 * 60 * 60 * 24 * 365, // 1 year
		waitSecondsBetween: 1000 * 60 * 60 * 24, // 1 day
		autoLaunch: true,
		cookieName: 'drammenSurveyClosed',
		survey: {
			link: 'popup.html'
		}
	});
};


function closeBrowser() {
//			alert('close');
	surveyTimer.saveSeconds();
}
function deleteCookie() {
	$.cookie('drmkSurveyTimer', null);
}
//		deleteCookie();
window.onbeforeunload = function(){
	var expDate = new Date();
	expDate.setTime(expDate.getTime() + 31536000000);
	$.cookie('drmkSurveyTimer', seconds, { expires: expDate });
};