var $_keepAliveEndpoint = '/portal/wlxapp/Ping.srv';
/**
 * Private convenience function that helps with the evaluation of function strings,
 * if the eval was sucessfull the function is return otherwhise null is returned.
 * @param functionStr The string to evaluate as a function.
 */
var $_createFunction = function(functionStr) {
    var func;
    if (functionStr) {
        try {func = eval(functionStr);} catch(e) {func = null;}
    }
    return func;
};
/**
 * Private function to help with calling the parent interface.
 * @param options The options that should be send to the function on the parent
 * interface.
 */
var $_callFunction = function(options) {
    var func;
    try {
        var functionStr = 'IFrameParentInterface.' + options.fn;
        func = $_createFunction('parent.'+functionStr);
        if (func){/*Function found!*/} else func = $_createFunction('parent.parent.'+functionStr);
        if (func){/*Function found!*/} else func = $_createFunction(functionStr);
    } catch(e) {}
    if (func) {return func(options.opts);}
};
var breadcrumbDefaults = {level:1,newLevels:new Array()[{display:null,url:null}]};
var rateThisPageDefaults = {enabled:false,ratePage:null};
var dialogDefaults = {callback:''};

var resizeHeight = 0;


function delayedResize(){
    var h = -1;

    if ($(document) && $(document).find('body')) {
        if ($.browser.msie) {
            var scrollHeight = 0;
            try {if (!h || h <= 0 && $(document).find('body').attr('scrollHeight')) scrollHeight=$(document).find('body').attr('scrollHeight');}catch(e){}
            if (scrollHeight>h) {h=scrollHeight;}
        } else {
            var offsetHeight = 0;
              try {
                 if (!h || h <= 0 && $(document).find('body').attr('offsetHeight')) {
                    offsetHeight=$(document).find('body').attr('offsetHeight');
                 }
                }catch(e){}
            if (offsetHeight>h) {h=offsetHeight;}
        }
        var clientHeight = 0;
        try {if (!h || h <= 0 && $(document).find('body').attr('clientHeight')) clientHeight=$(document).find('body').attr('clientHeight');}catch(e){}
        if (clientHeight>h) {h=clientHeight;}
    }

    if (h != resizeHeight){

        $_callFunction({fn:'resizeContainingIframe',opts:{height:h}});
        resizeHeight = h;
    }

}


/**
 * IFRAME client interface that wraps calls to the IFRAME parent interface.
 */
var IFrameInterface = jQuery.extend({
    /**
     * Reset the IFRAME's height to a specified height.
     */
    resetIframeHeight:function(resetHeight) {
		$_callFunction({fn:'resizeContainingIframe',opts:{height:resetHeight}});
	},
    /**
     * Resizes an IFRAME found on the parental DOM tree.
     */
    resizeIframe:function() {

        if (resizeInterval){
            clearInterval(resizeInterval);
        }

        var resizeInterval = setInterval("delayedResize()",2000);
    },
    /**
     * Keeps the current portal session alive by calling the ping endpoint
     */
    keepAlive:function()
    {
        //$_callFunction({fn:'keepSessionAlive'});
        $.ajax({
            type: "POST",
            url: $_keepAliveEndpoint
        });
    },
    /**
     * Update/modify the breadcrumb.
     * @param options Options to send to the parent interface.
     */
    breadcrumb:function(options) {
        var _opts = $.extend(breadcrumbDefaults, options || {});
        $_callFunction({fn:'breadcrumb',opts:_opts});
    },
    /**
     * Get the current size of the breadcrumb levels count.
     */
    breadcrumbSize:function() {
        return $_callFunction({fn:'breadcrumbSize'});
    },
    /**
     * Send information to the rate this page functionality to the parent interface.
     * @param options Options to send to the parent interface.
     */
    rateThisPage:function(options) {
        var _opts = $.extend(rateThisPageDefaults, options || {});
        $_callFunction({fn:'rateThisPage',opts:_opts});
    },
    initDialogs:function(options) {
        var _opts = $.extend(dialogDefaults, options || {});
        $('.dialog').click(function() {
            var dialogAnchor = $(this);
            var dId = dialogAnchor.attr('id');
            var src = dialogAnchor.attr('href');
            var width = dialogAnchor.attr('width');
            var height = dialogAnchor.attr('height');
            var modal = dialogAnchor.hasClass('modal');
            var chromeless = dialogAnchor.hasClass('chromeless');
            var hideClose = dialogAnchor.hasClass('hideClose');
            $_callFunction({fn:'showDialog',opts:{
                dialogId:dId,
                modal:modal,
                src:src,
                width:width,
                height:height,
                chromeless:chromeless,
                hideClose:hideClose,
                callback:_opts.callback
            }});
            return false;
        });
    },

    closeDialog:function(args) {
        $_callFunction({fn:'closeOpenDialog',opts:args});
    },

    /**
     * Register the trigger element (<a>) and target (<div>) for the modal
     * where options contains:
     * {trigger: <string - jq selector for trigger>, target: <string - jq selector for target div>, isIframe: <the string 'true' or 'false'>}
     *
     * @param opts
     */
    initModalDialog:function(opts) {
        var isIframe = $.trim(opts.isIframe);

        // get all the triggers that matched
        var $allTriggers = $(opts.trigger);

        if(isIframe == 'true')
        {
            $allTriggers.each(function ()
            {
                var $trigger = $(this);
                $trigger.click(function(){
                    //build options to pass to loadInIframeModal
                    var childOpts = {trigger: $trigger, target: opts.target, isIframe: opts.isIframe, scrolling: opts.scrolling, autoResize: opts.autoResize};
                    $_callFunction({fn:'loadInIframeModal', opts:childOpts});
                    return false;
                });
            });
        }else
        {
            $allTriggers.each(function ()
            {
                var $trigger = $(this);
                $trigger.click(function(){
                    //build options to pass to loadInIframeModal
                    var childOpts = {trigger: $trigger, target: opts.target, isIframe: opts.isIframe};
                    $_callFunction({fn:'loadInModal', opts:childOpts});
                    return false;
                });
            });
        }
    },

    showInModal:function(opts) {
        $_callFunction({fn:'showInModal', opts:opts});
    },
    hideModal:function() {
        $_callFunction({fn:'closeOpenJqmDialog',opts:{}});
    },

    /**
     * Log an event/pageview for analytics in the parent interface
     * @param opts
     * opts are:
     * url: the url to be logged for the pageview/event. Please send through proper context so that pages or events can be distinguished between.
     * Value for url must start with '/'
     */
    analyticsTrackPageview: function(opts) {
      var _opts = {url: opts.url};
      $_callFunction({fn:'analyticsTrackPageview', opts:_opts});
    }
});

/* Some autoscripts... */
$(function() {
    IFrameInterface.keepAlive();
    IFrameInterface.analyticsTrackPageview({url: document.location.pathname});
    $('.dialogCloser').click(function() {
        IFrameInterface.closeDialog();
        return false;
    });
});


