/**
* 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) {
        seconds = this.getSeconds(args);
        if ($.cookie('drammenSurveyClosed2010') == 'Yes')
            return false;
        seconds = this.getSeconds(args);
        this.timer;
        timer = setInterval(this.incrementSeconds, 1000);

    },

    getSeconds: function(args) {
        if (($.cookie('drammenSurveyClosed2010') == 'Yes'))
            $.cookie('drmkSurveyTimer', null)
        var timerCookie = $.cookie('drmkSurveyTimer');
        if (timerCookie) {
            return timerCookie;
        } else {
            return 0;
        }
    },

    incrementSeconds: function() {
        //		console.log(this.getSeconds());
        if (seconds < 60)
            seconds++;
        //		console.log(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.selector.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 {
            //console.log("do not show");
        }
    },

    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() - $(surveyWindow).outerHeight()) / 2 + $(window).scrollTop() + "px");
        $(surveyWindow).css("left", ($(window).width() - $(surveyWindow).outerWidth()) / 2 + $(window).scrollLeft() + "px");
    },

    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=off,scrollbars=off,height=800,width=800');		
            //			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=MmKRtX3boohB1kVmHFMq0w%3d%3d&password=tXz4YxEyVw0%3d', '', 'width=960,height=670,resizable=1,scrollbars=1');
        return objWindow;
    }


}

$(document).ready(function() {
    if (document.cookie) {
        var surveyTimer = new countSeconds({
            cookieName: 'drmkSurveyTime',
            cookieTime: 31536000000,
            timeLimit: 60 // seconds
        });
    }
    //	$('div#testSurvey').append($.cookie('drammenSurveyClosed2010'));
    //	$('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: 'drammenSurveyClosed2010',
        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 });
};
