﻿function setCookies()
{
    if (window.browseingId) {
        Cookie.set('cs_browse_id', browseingId, null, '/');
    } else {
        Cookie.remove('cs_browse_id', '/');
    }
    if (window.modeId) {
        Cookie.set('mode', window.modeId, null, '/');
    } else {
        Cookie.remove('mode', '/');
    }
}


function goBackIgnorePostback(defaultPage) {
    if (document.referrer != '' && !document.referrer.startsWith(window.location.protocol + '//' + window.location.host + window.location.pathname)) {
        window.location = document.referrer;
        return true;
    }
    if (defaultPage) window.location = defaultPage;
    return false;
}

function resizeToolbar() {
    var vtoolbar = $('vtoolbar');
    if (!vtoolbar) return;
    vtoolbar.setStyle({ right: 0 });
    var maxToolBarWidth;
    var innerTools = $('vtoolbar_interior_wrap');
    if (!innerTools.visible()) {
        innerTools.toggle();
        maxToolBarWidth = innerTools.getWidth();
        innerTools.toggle();
    }
    else maxToolBarWidth = innerTools.getWidth();
    if (vtoolbar) 
        vtoolbar.setStyle({ right: (document.viewport.getWidth() - maxToolBarWidth) / 2.0 + 'px' });
}
Event.observe(window, 'focus', setCookies);
Event.observe(window, 'resize', resizeToolbar);
document.observe('dom:loaded', resizeToolbar);

var Cookie = {
    get: function(name)
    {
        if (typeof (document.cookie) == 'string') {
            var start = document.cookie.indexOf(name + "=");
            var len = start + name.length + 1;
            if ((!start) && (name != document.cookie.substring(0, name.length))) {
                return null;
            }
            if (start == -1) return null;
            var end = document.cookie.indexOf(";", len);
            if (end == -1) end = document.cookie.length;
            return decodeURIComponent(document.cookie.substring(len, end));
        } else {
            /* document.cookie is not a string so return an
            empty string. When tested this will type-convert to
            boolean false (accurately) giving the impression that
            client-side cookies are not available on this system:-
            */
            return "";
        }
    },
    set: function(name, value, expires, path, domain, secure)
    {
        if (typeof (document.cookie) == 'string') {
            document.cookie = name + "=" + encodeURIComponent(value) +
            ((expires) ? ";expires=" + expires.toGMTString() : "") +
            ((path) ? ";path=" + path : "") +
            ((domain) ? ";domain=" + domain : "") +
            ((secure) ? ";secure" : "");
        } //else document.cookie is not a string so do not write to it.
    },
    remove: function(name, path, domain)
    {
        if (this.get(name)) {
            document.cookie = name + "=" +
       ((path) ? ";path=" + path : "") +
       ((domain) ? ";domain=" + domain : "") +
       ";expires=Thu, 01-Jan-70 00:00:01 GMT";
        }
    },
    accept: function()
    {
        if (typeof navigator.cookieEnabled == 'boolean') {
            return navigator.cookieEnabled;
        }
    }
};

//session validation functions
function validateSession() 
{
   if (!isSessionValid()) 
   {
      redirectToLogin();
      return false
   }
   return true;
}
function isSessionValid()
{
   //Validate the request to make sure the user's session is still good
   var valid = false;
   new Ajax.Request('/admin/Authenticator.ashx', {
      method: 'get',
      asynchronous : false,
      onSuccess : function() { valid = true; },
      onFailure : function() { valid = false; }
   });
   return valid;
}
function redirectToLogin()
{
   window.location.assign('/admin/?ReturnUrl=' + encodeURIComponent(window.location.pathname));
}

window.showUrl = function(url, options) {
    var acuWindow = new AcuWindowLite(url, options);
    Window.keepMultiModalWindow = true;
}
if (!window.top.currentWindows) {
    window.top.currentWindows = new $A();
    window.top.currentContext = window.top;
    window.top.currentWindows[0] = window.top;
}
var AcuWindowLite = Class.create({
    initialize: function(url, options) {
        this.options = {
            height: '300px',
            width: '400px',
            modal: true,
            onSuccess: null,
            onCancel: null,
            className: 'alphacube',
            minimizable: false,
            maximizable: false,
            closeCallback: this.onclose.bindAsEventListener(this),
            destroyOnClose: true,
            showEffectOptions: { afterFinish: this.onWindowRendered.bind(this) }
        }
        this.url = url;
        this.options = Object.extend(this.options, options);
        this.window = new Window(this.options);
        this.window.setStatusBar('<img src="/style/pw_default/progressbar.gif" />');
        this.window.showCenter(this.options.modal);
    },
    onWindowRendered: function() {
        if (this.window && this.url) this.window.setURL(this.url);
        var frame = this.window.getContent();
        Event.observe(frame, 'load', function() { if (this.window) this.window.setStatusBar('&nbsp;'); } .bind(this));
        frame.setSuccess = this.setSuccess.bind(this);
        frame.setCancel = this.setCancel.bind(this);
        window.top.currentContext = this.window.content.contentWindow;
        window.top.currentWindows[window.top.currentWindows.length] = window.top.currentContext;
    },
    setSuccess: function(state) {
        if (this.window) {
            this.success = true;
            if (this.options.onSetSuccess) this.options.onSetSuccess();
            if (this.options.onSuccess) this.options.onSuccess(state);
            this.window.close();
        }
    },
    setCancel: function(state) {
        if (this.window) {
            this.success = false;
            if (this.onSetCancel) this.onSetCancel();
            if (this.options.onCancel) this.options.onCancel(state);
            this.window.close();
        }
    },
    onclose: function() {
        if (this.onSetCancel) this.onSetCancel();
        window.top.currentWindows = window.top.currentWindows.reject(function(currentWindow) { return currentWindow == window.top.currentContext });
        window.top.currentContext = window.top.currentWindows[window.top.currentWindows.length - 1]
        this.window = null;
        return true;
    }
});

//begin General Window (used for non-tool specific window instances)
window.Manager = 
{
   windows : [],   
   canShow : function(acuWindow)
   {
      // Make sure that they are logged in and that they are not trying to open a window that is already open
      return !this.getWindow(acuWindow.divId);
   },
   
   addWindow : function(acuWindow) 
   {
      // Don't center the parent window to avoid making it visible on scroll
      if (this.windows.length > 0)
         this.windows[this.windows.length - 1].__window.centered = false;
         
      // Create a new generic window, show it, and add it to the list of open windows
     this.windows.push(acuWindow);

      
   },
  // Gets window from its id
  getWindow: function(id) {
    return this.windows.detect(function(window) { return window.divId == id });
  },
  
  removeWindow: function(id) 
  {
    this.getWindow(id).__window.centered = false;
    this.windows = this.windows.reject(function(window) { return window.divId==id });
    
    // Recenter the the last window
    if (this.windows.length > 0)
    {
      this.windows[this.windows.length - 1].__window.centered = true;
      this.windows[this.windows.length - 1].__window._recenter();
    }
  }
}

var AcuWindow = Class.create();
AcuWindow.prototype =
{
    divId: null,
    baseUrl: '',
    successCallback: null,
    cancelCallback: null,
    skipValidation: false,
    width: 250,
    height: 250,
    modal: true,
    __window: null,
    userData: null,
    success: null,
    queryString: null,
    initialize: function() { },
    show: function(querystring, successCallback, cancelCallback) {
        this.success = null;
        if (successCallback) this.successCallback = successCallback;
        if (cancelCallback) this.cancelCallback = cancelCallback;

        if (!this.skipValidation && !isSessionValid()) { redirectToLogin(); return; }
        // Call the mananger to verify this window can be opened
        if (!window.Manager.canShow(this)) return;
        if (!this.__window) {
            var windowSize = WindowUtilities.getPageSize();
            this.__window = new Window({ id: this.divId, className: 'alphacube', minimizable: false, maximizable: false, width: null, height: null, closeCallback: this.__onclose.bindAsEventListener(this), destroyOnClose: true, showEffectOptions: { beforeStart: this.onWindowLoad.bindAsEventListener(this), afterFinish: this.onWindowRendered.bindAsEventListener(this) }, maxWidth: windowSize.windowWidth - 50, maxHeight: windowSize.windowHeight - 50 });
            Window.keepMultiModalWindow = true;
            WindowCloseKey.init(null);
        }
        this.queryString = querystring;
        this.__window.setStatusBar('<img src="/core/style/pw_default/progressbar.gif" />');
        this.__window.setSize(this.width, this.height);
        this.__window.showCenter(this.modal);
        window.Manager.addWindow(this);
    },
    onWindowRendered: function() {
        this.__window.setURL(this.queryString ? this.baseUrl + "?" + this.queryString : this.baseUrl);
        var frame = this.__window.getContent();
        Event.observe(frame, 'load', this.contentLoaded.bindAsEventListener(this));
        frame.setSuccess = this.setSuccess.bindAsEventListener(this);
        frame.setCancel = this.setCancel.bindAsEventListener(this);

        window.top.currentContext = this.__window.content.contentWindow;
        window.top.currentWindows[window.top.currentWindows.length] = window.top.currentContext;
    },
    onWindowLoad: function() { },
    contentLoaded: function() {
        if (this.__window) {
            this.__window.setStatusBar('&nbsp;');
            if (!this.__window.getContent().contentWindow || this.__window.getContent().contentWindow.document.documentElement == null) return; // Todo: find out why this is null on quick window reloads
            var item = this.__window.getContent().contentWindow.document.documentElement;
            if (item) {
                var w = item.scrollWidth;
                var h = item.scrollHeight;
                if (Prototype.Browser.Gecko) {
                    h = item.offsetHeight;
                }
                this.setSize(w, h);
            }
        }
    },
    setSize: function(width, height) {
        if (this.__window) {
            if (width) this.width = width;
            if (height) this.height = height;
            this.__window.setSize(this.width, this.height, true);
            this.__window._center();
        }
    },
    setSuccess: function(state) {
        if (this.__window) {
            this.success = true;
            if (this.onSetSuccess) this.onSetSuccess();
            if (this.successCallback) this.successCallback(state);
            this.__window.close();
        }
    },
    setCancel: function(state) {
        if (this.__window) {
            this.success = false;
            if (this.onSetCancel) this.onSetCancel();
            if (this.cancelCallback) this.cancelCallback(state);
            this.__window.close();
        }
    },
    __onclose: function() {
        // if the success was not set (they clicked the close button) and there is a cancel callback, 
        // treat this as a cancel
        if (!(this.success)) {
            if (this.onSetCancel) this.onSetCancel();
            if (this.cancelCallback) this.cancelCallback();
        }
        //let the window know that it can close
        if (this.onClose) this.onClose();
        window.Manager.removeWindow(this.divId);
        this.__window = null;

        window.top.currentWindows = window.top.currentWindows.reject(function(currentWindow) { return currentWindow == window.top.currentContext });
        window.top.currentContext = window.top.currentWindows[window.top.currentWindows.length - 1]
        return true;
    },
    isVisible: function() {
        return (this.__window && this.__window.visible);
    }
}
//end General Window (used for non-tool specific window instances)

var EmailAFriend = Class.create(AcuWindow,
{
   initialize: function() 
   {
      this.divId = "__email_a_friend";
      this.baseUrl = "/email_a_friend.aspx",
      this.height = 550;
      this.width = 550;
      this.skipValidation = true;
   }
});
window.EmailAFriend = new EmailAFriend();

// End Static window declarations

// Reset the session timer on each page request
var loginTimer;
var sessionTimer;
Event.observe(window, 'load', function() {
    if(window.top.resetSessionTimer) window.setTimeout(window.top.resetSessionTimer, 150);
});

function focusElements() {
    $$('.focus_element').each(function(element) {
        var height = element.getHeight() + 'px';
        element.setStyle({ zIndex: 50, background: 'white', position: 'absolute' });
        element.wrap('div', { style: 'position:relative' }).setStyle({ height: height });
    });
}
function focusElement(id) {
    element = $(id);
    var height = element.getHeight() + 'px';
    element.setStyle({ zIndex: 50, background: 'white', position: 'absolute' });
    element.wrap('div', { style: 'position:relative' }).setStyle({ height: height });
}
