﻿var storeTimerId = null;

$(document).ready(function() {
    RestorePosition();
});

/* IMPORANT pageLoad is used to support restoring the scroll position on post back */
/*function pageLoad() {
    RestorePosition();
}*/

$(window).scroll(function() {
    ClearStoreTimer();
    SetStoreTimer();
});

function SetStoreTimer() {
    storeTimerId = setTimeout(StorePosition, 250);
}

function ClearStoreTimer() {
    if (storeTimerId != null) {
        clearTimeout(storeTimerId);
        storeTimerId = null;
    }
}

function SetCookie(name, value, expiry, path, domain, secure) {
    var docCookie = name + '=' + escape(value) +
        ((expiry) ? '; expires=' + expiry.toGMTString() : '') +
        ((path) ? '; path=' + path : '') +
        ((domain) ? '; domain=' + domain : '') +
        ((secure) ? '; secure' : '');

    document.cookie = docCookie;

    return true;
}

function GetCookie(name) {
    var value = null;
    var docCookie = document.cookie;
    var start = docCookie.indexOf(name + '=');
    var finish = -1;

    if (start >= 0) {
        start = start + name.length + 1;
        finish = docCookie.indexOf(';', start);

        if (finish < 0)
            finish = docCookie.length;

        value = unescape(docCookie.substring(start, finish));
    }

    return value;
}

function StorePosition() {
    var scrollX = 0;
    var scrollY = 0;

    if (document.documentElement) {
        scrollX = Math.max(document.documentElement.scrollLeft, document.body.scrollLeft);
        scrollY = Math.max(document.documentElement.scrollTop, document.body.scrollTop);
    } else if (document.body && typeof (document.body.scrollTop) != 'undefined') {
        scrollX = document.body.scrollLeft;
        scrollY = document.body.scrollTop;
    } else if (typeof (window.pageXOffset) != 'undefined') {
        scrollX = window.pageXOffset;
        scrollY = window.pageYOffset;
    }

    var name = 'scrollPosition';
    var value = scrollX + ';' + scrollY;

    this.SetCookie(name, value);

    return true;
}

function RestorePosition() {
    var name = 'scrollPosition';
    var value = this.GetCookie(name);

    if (typeof (value) != 'undefined' && value) {
        var scrollCoords = value.split(';');
        var scrollX = parseInt(scrollCoords[0]);
        var scrollY = parseInt(scrollCoords[1]);
        //var expiry = new Date();

        //expiry.setTime(expiry.getTime() - 1);

        //expire the cookie
        //setCookie(name, null, expiry)

        //scroll to the recovered position
        window.scrollTo(scrollX, scrollY);

        return true;
    } else {
        return false;
    }
}
