/* Liberty Mutual Custom Entrance/Exit Survey */
/* author Benjamin Wilson ben.wilson@valtira.net */

/*
Cookies with description of each:

vlt_firstEntrance - set only if google entrance-variation is choosen and it's the user's first visit (expires @ session end)
vlt_entranceVariation - set if entrance-variation is loaded via google (expires @ session end)
vlt_entranceOffer - set when the entrance survey offer has been made, we only show entrance once (expires never, it's sticky)
vlt_entranceTaken - set if the visitor opts-in to the survey, used to not bother them afterwards (expires never)
vlt_exitVariation - set if exit-variation is loaded via google (expires @ session end)
vlt_exitOffer - set when the exit survey offer has been made (!Important expires @ session end)
vlt_exitTaken - set if the visitor opts-in to the survey, used to not bother them on subsequent visits (expires never)
vlt_pageViews - keeps count of how many pages have been viewed, at a specific number exit survey is shown (expires @ session end)

*/


/* Global Vars

vlt_pageCount - this var works with the vlt_pageViews cookie to determine when to show the exit survey
vlt_oldY - var is used to determine mouse direction
vlt_externalPath - stores external path to redirect on exit popup
vlt_refUrl - is passed to the survey to track what website lead the visitor to the current site
vlt_entrancePopupPath - url path to the popup for the opt-in entrance survey
vlt_exitPopupPath - url path to the popup for the opt-in exit survey

*/
var vlt_pageCount = 5;
var vlt_oldY = 0;
var vlt_externalPath = "";
var vlt_refUrl = "";
var vlt_entrancePopupPath = "/common/html/valtira/popup.html";
var vlt_exitPopupPath = "/common/html/valtira/exitpopup.html";


/* Functions

vlt_offerEntrance - brings a thickbox up, allowing the visitor to opt-in for entrance survey
vlt_offerExit - brings a thickbox up, allowing the visitor to opt-in for exit survey
vlt_listenForExit - sets mouse and external link listeners to bring up thickbox for exit survey
vlt_redirectExternalLink - takes a path and redirects browser to the path provided
vlt_openSurvey - creates a new window where the visitor can take the survey
vlt_initThickboxSurveyLink - sets up links in thickbox to open survey

--- Provided from http://techpatterns.com/downloads/javascript_cookies.php
vlt_Get_Cookie
vlt_Set_Cookie
vlt_Delete_Cookie

*/
function vlt_offerEntrance() {
    // Launch MODAL BOX
    var t = setTimeout("tb_show('Welcome', vlt_entrancePopupPath+'?height=180&width=300', '')", 1000);
    /* Set vlt_entranceOffer cookie - don't expire only shown once,
    all subsequent visits exit survey only */
    vlt_Set_Cookie('vlt_entranceOffer', 'true', '1000', '/', '', '');
    /* Set vlt_entranceOffer cookie - don't expire only shown once,
    all subsequent visits exit survey only */
    vlt_Set_Cookie('vlt_firstEntrance', 'true', '', '/', '', '');
}


function vlt_offerExit() {
    // Launch MODAL BOX
    tb_show("", vlt_exitPopupPath + "?height=180&width=300", "");
    /* Set vlt_exitOffer cookie - expires at end of session */
    vlt_Set_Cookie('vlt_exitOffer', 'true', '', '/', '', '');
}


function vlt_listenForExit() {

    /* If visitor leaves page, show exit survey */
    $(document).mousemove(function(e) {

        // figure out the offset if they visitor has scrolled	
        var vlt_scrOfY = 0;
        if (typeof (window.pageYOffset) == 'number') {
            //Netscape compliant
            vlt_scrOfY = window.pageYOffset;
        } else if (document.body && (document.body.scrollLeft || document.body.scrollTop)) {
            //DOM compliant
            vlt_scrOfY = document.body.scrollTop;
        } else if (document.documentElement && (document.documentElement.scrollLeft || document.documentElement.scrollTop)) {
            //IE6 standards compliant mode
            vlt_scrOfY = document.documentElement.scrollTop;
        }

        var vlt_offSetTop = e.pageY - vlt_scrOfY;

        if (vlt_offSetTop <= 5 && e.pageY < vlt_oldY && !vlt_Get_Cookie('vlt_exitOffer')) {
            vlt_offerExit();
        }
        //set new position for next check
        vlt_oldY = e.pageY;
    });

    /* Find all external links and offer exit survey before redirect */
    $('a').filter(function() {
        return this.hostname && this.hostname !== location.hostname;
    }).click(function() {
        if (!vlt_Get_Cookie('vlt_exitOffer')) {
            vlt_offerExit();
            vlt_externalPath = this.href;
            var vlt_path = this.href;
            setTimeout('vlt_redirectExternalLink("' + vlt_path + '");', 8000);
            return false;
        } else {
            return true;
        }
    });
}


function vlt_redirectExternalLink(path) {
    location.href = path;
}


function vlt_openSurvey(pageURL, title, w, h) {
    var vlt_left = (screen.width / 2) - (w / 2);
    var vlt_top = (screen.height / 2) - (h / 2);
    var vlt_pUrl = pageURL + "?referringUrl=" + vlt_refUrl + "&lastPage=" + document.title;
    var vlt_targetWin = window.open(vlt_pUrl, '', 'toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=yes, resizable=no, copyhistory=no, width=' + w + ', height=' + h + ', top=' + vlt_top + ', left=' + vlt_left);
}


function vlt_initThickboxSurveyLink() {
    // setup link for either enterance or exit survey
    $("a#surveyLink").click(function() {
        // set survey taken cookie based on entranceVariation or exitVariation cookie
        if (vlt_Get_Cookie('vlt_entranceVariation')) {

            vlt_Set_Cookie('vlt_entranceTaken', 'true', '1000', '/', '', '');

        } else {

            vlt_Set_Cookie('vlt_exitTaken', 'true', '1000', '/', '', '');

        }

        vlt_openSurvey(this.href, "Liberty Mutual Survey", 500, 600);

        return false;
    });
    $("a#redirectNow").click(function() {
        $(this).attr('href', vlt_externalPath);
    });
}


function vlt_Set_Cookie(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" : "");
}


function vlt_Get_Cookie(check_name) {
    // first we'll split this cookie up into name/value pairs
    // note: document.cookie only returns name=value, not the other components
    var a_all_cookies = document.cookie.split(';');
    var a_temp_cookie = '';
    var cookie_name = '';
    var cookie_value = '';
    var b_cookie_found = false; // set boolean t/f default f

    for (i = 0; i < a_all_cookies.length; i++) {
        // now we'll split apart each name=value pair
        a_temp_cookie = a_all_cookies[i].split('=');


        // and trim left/right whitespace while we're at it
        cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');

        // if the extracted name matches passed check_name
        if (cookie_name == check_name) {
            b_cookie_found = true;
            // we need to handle case where cookie has no value but exists (no = sign, that is):
            if (a_temp_cookie.length > 1) {
                cookie_value = unescape(a_temp_cookie[1].replace(/^\s+|\s+$/g, ''));
            }
            // note that in cases where cookie is initialized but no value, null is returned
            return cookie_value;
            break;
        }
        a_temp_cookie = null;
        cookie_name = '';
    }
    if (!b_cookie_found) {
        return null;
    }
}


// this deletes the cookie when called
function vlt_Delete_Cookie(name, path, domain) {
    if (vlt_Get_Cookie(name)) document.cookie = name + "=" +
  ((path) ? ";path=" + path : "") +
  ((domain) ? ";domain=" + domain : "") +
  ";expires=Thu, 01-Jan-1970 00:00:01 GMT";
}




/* On load functionality */
$(document).ready(function() {

    /* check for referral URL */
    /* this code is to provide the referral url from the first page of the site
    if not from an off-site link, then it's set to the first page
    */
    if (vlt_Get_Cookie('vlt_refUrl')) {
        // var is passed into the survey call
        vlt_refUrl = vlt_Get_Cookie('vlt_refUrl');
    } else {
        vlt_refUrl = document.referrer;
        vlt_Set_Cookie('vlt_refUrl', vlt_refUrl, '', '/', '', '');
    }

    /* First check pageViews cookie
    After x number of pages show exit survey (number set in showSurveyPageNumber var)
    */
    if (vlt_Get_Cookie('vlt_pageViews')) {
        var vlt_pageViews = parseInt(vlt_Get_Cookie('vlt_pageViews')) + 1;
        // showSurveyPageNumber is set in the global vars of this page
        if (vlt_pageViews == vlt_pageCount) {
            // only offer the exit survey if the visitor has never taken the survey and hasn't been offered this time
            var vlt_exitTaken = vlt_Get_Cookie('vlt_exitTaken');
            var vlt_entranceTaken = vlt_Get_Cookie('vlt_entranceTaken');
            var vlt_firstEntrance = vlt_Get_Cookie('vlt_firstEntrance');
            var vlt_exitOffer = vlt_Get_Cookie('vlt_exitOffer');
            if (!vlt_Get_Cookie('vlt_exitTaken') && !vlt_Get_Cookie('vlt_entranceTaken') && !vlt_Get_Cookie('vlt_firstEntrance') && !vlt_Get_Cookie('vlt_exitOffer')) {
                var t = setTimeout("vlt_offerExit ()", 1000);
            }
        }
        vlt_Set_Cookie('vlt_pageViews', vlt_pageViews, '', '/', '', '');
    } else {
        // create cookie and set pageViews to 1
        vlt_Set_Cookie('vlt_pageViews', '1', '', '/', '', '');
        var vlt_pageViews = 1;
    }
    /* END check pageViews */



    /* if it's the first time with an entrance variation, show popup immediately */
    var vlt_entranceVariation = vlt_Get_Cookie('vlt_entranceVariation');
    var vlt_entranceOffer = vlt_Get_Cookie('vlt_entranceOffer');
    if (vlt_Get_Cookie('vlt_entranceVariation') && !vlt_Get_Cookie('vlt_entranceOffer')) {
        vlt_offerEntrance();
    }



    /* This code block determines if we should listen for exit survey events */
    // check if user hasn't already taken a survey
    // also check if it's there first time with entrance survey which is only shown once
    // finally check if exitOffer was set (from pageViews trigger threshold being crossed)
    if (!vlt_Get_Cookie('vlt_entranceTaken') && !vlt_Get_Cookie('vlt_exitTaken') && !vlt_Get_Cookie('vlt_firstEntrance') && !vlt_Get_Cookie('vlt_exitOffer')) {
        vlt_listenForExit();
    }
});