﻿/// <reference path="../JQuery/jquery-1.3.2-vsdoc.js" />
/// <reference path="../JQuery/jqeury.Include.js" />
/// <reference path="../JQuery/jquery.boxy.js" />

if (typeof console == "undefined") {
    console = {};
    console.log = function() { };
    console.dir = function() { };
}

if (!Function.CreateDelegate) {
    Function.CreateDelegate = function(instance, method) {
        return function() {
            method.apply(instance, arguments);
        }
    }
}

if (typeof hyz == "undefined") hyz = {};
if (!hyz.config) hyz.config = {};
$.extend(hyz.config, {
    jqueryInclude_scriptUrl: "/ui/js/jquery/jqeury.Include.js",
    jqueryBoxy_scriptUrl: "/ui/js/jquery/jquery.boxy.js",
    jqueryBoxy_cssUrl_general: "/ui/css/jquery.boxy.css",
    jqueryBoxy_cssUrl_ie: "/ui/css/jquery.boxy.ie.css",
    emptyGuid: "{00000000-0000-0000-0000-000000000000}"
});

// hyz.eventHandler
if (typeof hyz.eventHandler == "undefined") {
    hyz.eventHandler = function hyz$eventHandler(dels) {
        if (dels)
            this.dels = dels;
        else
            this.dels = new Array();
    }
    hyz.eventHandler.prototype.dels = null;
    hyz.eventHandler.prototype.add = function(f) {
        this.dels.push(f);
    }
    hyz.eventHandler.prototype.call = function(data) {
        if (this.dels)
            for (var i = 0, l = this.dels.length; i < l; i++)
            this.dels[i](data);
    }
}

// hyz.runWhenAConditionIsValid
hyz.runWhenAConditionIsValid = function hyz$runWhenAConditionIsValid(f, condition, timeInterval, maxTries, onFail, _currentTry) {
    if (!_currentTry)
        _currentTry = 0;
    _currentTry++;
    if (maxTries && maxTries > 0) {
        if (_currentTry > maxTries) {
            if (onFail)
                onFail();
            return;
        }
    }
    if (!condition()) {
        setTimeout(function() {
            hyz.runWhenAConditionIsValid(f, condition, timeInterval, maxTries, onFail, _currentTry);
        }, timeInterval);
    } else
        f();
}

// hyz.popup
hyz.popup = function(id, url, options) {
    this.options = $.extend({
        fullScreen: false,
        getWidth: function() { return 500; },
        getHeight: function() { return 400; }
    }, options);
    if (this.options.fullScreen) {
        this.options.getWidth = function() {
            return $(document).width() - 10;
        };
        this.options.getHeight = function() {
            return $(document).height() - 10;
        };
    }
    this.id = id;
    this.url = url;
    this.cancel = new hyz.eventHandler();
    this.commit = new hyz.eventHandler();
    this.proceedingToNextStep = new hyz.eventHandler();

    var init = Function.CreateDelegate(this, this._init);
    $.include(hyz.config.jqueryBoxy_scriptUrl, function() { init(); });
    $.include(hyz.config.jqueryBoxy_cssUrl_general, function() { });
    if ($.browser.msie)
        $.include(hyz.config.jqueryBoxy_cssUrl_ie, function() { });
};
hyz.popup.prototype = {
    id: "",
    url: "",
    _initialized: false,
    _init: function() {
        // is being called after the dialog box logic is loaded
        if (this._initialized) return;
        this.container = $("<div id='popup_" + this.id + "'><iframe frameborder='0' src='about:blank'></iframe></div>");
        $(document.body).append(this.container);
        this._initialized = true;
    },
    _runWhenIFrameIsReady: function(f, whenRefreshed) {
        /// <param name='whenRefreshed'>f is only being ran if the iframe has been refreshed</param>
        var unqiueViewId = null;
        if (this.popupwin && this.popupwin.unqiueViewId)
            unqiueViewId = this.popupwin.unqiueViewId;
        var box = this.container;
        var iframeElement = box.find("iframe").get(0);
        var iframeLoaded = Function.CreateDelegate(this, function() {
            this.popupwin = iframeElement.contentWindow.hyz.popup.win;
            this.popupwin.popup = this;
            if (f)
                f();
        });
        hyz.runWhenAConditionIsValid(iframeLoaded, function() {
            iframeElement = box.find("iframe").get(0);
            if (typeof iframeElement == "undefined") return false;
            var b = iframeElement.contentWindow;
            if (b) {
                var h = b.hyz;
                if (h) {
                    if (whenRefreshed) {
                        if (h.popup.win) {
                            var d = h.popup.win.unqiueViewId;
                            if (d != unqiueViewId)
                                return true;
                            else return false;
                        } else {
                            return false;
                        }
                    } else {
                        if (h.popup.win)
                            return true;
                        else return false;
                    }
                }
            }
            return false;
        }, 500, 100, function() { alert("Failed") });
    },

    run: function(f) {
        ///<summary>runs the f in the context of the popup iframe, where this reffers to the window object of the iframe.</summary>
        console.log("hyz.popup.run");
        var _this = this;
        this._runWhenIFrameIsReady(function() {
            console.log("hyz.popup.run._runWhenIFrameIsReady calling f");
            var box = _this.container;
            var iframeElement = box.find("iframe").get(0);
            var win = iframeElement.contentWindow;
            var del = Function.CreateDelegate(win, f);
            del();
        }, false);
    },

    container: $(),
    boxy: null,
    popupwin: null, // a reference to the popup.win object in the popup window

    cancelled: false,
    cancel: new hyz.eventHandler(),
    onCancel: function(data) { if (typeof console != "undefined") console.log("Popup cancelled"); this.cancelled = true; this.cancel.call(data); },

    proceedingToNextStep: new hyz.eventHandler(),
    onProceedingToNextStep: function(data) {
        console.log("onProceedingToNextStep()");
        var _this = this;
        this._runWhenIFrameIsReady(function() { console.log("onProceedingToNextStep() _runWhenIFrameIsReady()"); /*alert(_this.popupwin.activeViewId);*/ }, true);
        this.proceedingToNextStep.call(data);
    },


    committed: false,
    commit: new hyz.eventHandler(),
    onCommit: function(data) { this.committed = true; this.commit.call(data); },

    center: function() {
        this.boxy.resize(this.options.getWidth(), this.options.getHeight());
        this.iframe.width(this.options.getWidth());
        this.iframe.height(this.options.getHeight());
        this.boxy.center();
    },

    iframe: null,

    onViewActivated: function(viewId) {
    },
    open: function(onOpened) {
        var open = function() {
            var box = this.container;
            var iframe = box.find("iframe");
            this.iframe = iframe;
            var iframeElement = iframe.get(0);
            iframeElement.contentWindow.document.write("loading...");
            var url = this.url;
            if (url.search((/\?/)) < 0)
                url += "?__homam=homam"
            iframe.attr("src", url + "&" + Math.random());
            this._runWhenIFrameIsReady(function() { });
            this.boxy = new Boxy(box, {
                draggable: false,
                title: '&nbsp;',
                afterHide: function() {
                }
            });
            if (this.options.fullScreen)
                $(this.boxy.getWrapper()).addClass("no-shade");
            this.center();
            $(window).resize(Function.CreateDelegate(this, this.center));
            if (onOpened)
                onOpened();
        }
        var del = Function.CreateDelegate(this, open);
        var _this = this;
        hyz.runWhenAConditionIsValid(del, function() { return _this._initialized; }, 500, 100, function() { alert("Failed") });
    },
    close: function() {
        this.boxy.hide();
    }
};