﻿var keyFieldName = "ctl00_gcKeys";
var authFieldName = "ctl00__auth";
var criteriaFieldName = "ctl00__criteria";
var criteriaTyepFieldName = "ctl00__criteriaType";
var keys = null;

$(document).ready(function () {
    var hidden = $("#" + keyFieldName);
    if (hidden != null && hidden != undefined)
        keys = hidden.val();

    $(document).delegate("a[href]:not([target=_blank]):not([href*='__doPostBack']):not([href*='WebForm_DoPostBackWithOptions']):not('.Bookmark'):not('.dxgvCommandColumnItem_EpiqDefault'):not([href*='javascript:'])", 'click', function (e) {
        gc();
    });

    $(document).delegate("a[href]:not([target=_blank]):not([href*='__doPostBack']):not([href*='WebForm_DoPostBackWithOptions']):not('.menu_r > a'):not('.Bookmark'):not('.dxgvCommandColumnItem_EpiqDefault'):not([href*='javascript:']):not('.ecsshtmlhomepage a')", "click", function (e) {
        redirect(this.href);
        return false;
    });

    $(document).delegate("a[href*='__doPostBack']:not([target=_blank])", 'click', function (e) {
        if (!va(e)) return false;
    });

    $(document).delegate("a[href*='WebForm_DoPostBackWithOptions']:not([target=_blank])", 'click', function (e) {
        if (!va(e)) return false;
    });

    $(document).delegate("input[type=submit]:not([id*=_login])", 'click', function (e) {
        if (!va(e)) return false;
    });

    $.history.init(sink);
});

function sink(url) {
	gc();
	redirect(url);
}

function gc() {
    if (PageMethods != undefined && PageMethods != null && keys != null && keys != "")
	    PageMethods.SessionGC(keys);
}

function va() {
	if ($('#' + authFieldName) == null || $('#' + authFieldName).val() == undefined) return true;

	var auth = false;
	var key = 'AUTH=';
	var i = document.cookie.indexOf(key);
	if (i != -1) {
		var n = document.cookie.indexOf(';', i);
		if (n == -1) n = document.cookie.length;

		auth = unescape(document.cookie.substring(i + key.length, n));
	}
	if (auth != $('#' + authFieldName).val()) {
		if (confirm('Your login status has changed since this page was loaded. In order to continue, this page must be reloaded.')) {
			window.location = document.location.href;
		}
		return false;
	}
	return true;
}

function redirect(url) {
	var criteria = $("#" + criteriaFieldName).val();
	var criteriaType = $("#" + criteriaTyepFieldName).val();
	if (PageMethods != undefined && PageMethods != null && criteria != null && criteria != "")
		PageMethods.BeforeNavigateWithCriteria(url, criteria, criteriaType, function(result) {
			if (result != null && result != undefined && result != "") {
				window.location = result;
			}
			else {
				window.location = url;
			}
		});
	else {
		window.location = url;
	}
}
