//global settings
ivj.problem_post_url = 'http://www.intelesense.net/user/ivjreport/';

/**
* Add the java applet to the page. To modify attributes and parameters use the
* two objects defined in this method. mayscript and scriptable are added automatically.
*
* @method
* @return void
*/
ivj.prototype.add_applet = function()
{
    $.log("Method: add_applet (build applet tag and write to page)");
    try
    {
        //Create applet HTML and return object reference
        var attributes = {
            'id':this.settings.id,
            'class':'ivj-applet',
            'name':'ivjApplet',
            'style':'width:100%;height:'+ (this.height - (this.settings.controls ? 20 : 0)) +'px" ',
            'code':'org.jdesktop.applet.util.JNLPAppletLauncher',
            'archive':this.settings.path+'applet/applet-launcher.jar, ' +
                this.settings.path+'applet/BrowserLauncher2-10.jar, ' +
                this.settings.path+'applet/commons-codec-1.5.jar, ' +
                this.settings.path+'applet/forms-1.2.1.jar, ' +
                this.settings.path+'applet/gson-1.7.1.jar, ' +
                this.settings.path+'applet/jackson-all-1.6.3.jar, ' +
                this.settings.path+'applet/JavaFTP.jar, ' +
                this.settings.path+'applet/jxlayer.jar, ' +
                this.settings.path+'applet/l2fprod.jar, ' +
                this.settings.path+'applet/macwidgets.jar, ' +
                this.settings.path+'applet/plugin.jar, ' +
                this.settings.path+'applet/ssllib.jar, ' +
                this.settings.path+'applet/SuperCSV-with_src-1.52.jar, ' +
				this.settings.path+'applet/swing3d.jar, ' +
                this.settings.path+'applet/TimingFramework-1.0.jar, ' +
                this.settings.path+'applet/worldwindx.jar, ", ' +
                this.settings.path+'applet/worldwind.jar, ' +
                'http://portals.intelesense.net/inteleview/common/jogl/jogl.jar, ' +
                'http://portals.intelesense.net/inteleview/common/jogl/gluegen-rt.jar, ' +
                this.settings.path+'applet/inteleview.jar'
        };
        var params = {
            'authtoken':this.settings.auth_token,
            'codebase_lookup':'false',
            'subapplet.classname':'net.intelesense.inteleview.InteleviewApplet',
            'subapplet.displayname':'InteleView 3.0 Web',
            'noddraw.check':'true',
            'progressbar':'true',
            'cache_option':'no',
            'separate_jvm':'true',
            'showWPS':'true',
            'showSidePanel':this.settings.show_side_panel,
            'customHierarchy':this.settings.hierarchy,
            'jnlpNumExtensions':'2',
            'appletId':this.settings.id,
            'user_group':this.settings.group_id,
            'navigateFunctionName':'follow_link',
            'jnlpExtension1':'http://portals.intelesense.net/inteleview/common/jogl/jogl.jnlp',
			'jnlpExtension2':'http://portals.intelesense.net' + this.settings.path + 'applet/webview.jnlp',
            'java_arguments':'-Xmx512m -Dsun.java2d.noddraw=true -Dsun.awt.noerasebackground=true'
        };
        this.object = $(this.get_tag(attributes,params));

        //Add applet to container DIV
        var container = $('<div class="ivj-container" id="'+this.settings.id+'-container"></div>')
            .width(this.width)
            .height(this.height)
            .css({
                'top':this.offset.top + 'px',
                'left':this.offset.left + 'px',
                'z-index':9999
            })
            .mousewheel(function(){return false;})
            .append(this.object);

        //Add controls (full screen etc) to container if requested
        if(this.settings.controls)
        {
            $.log("Adding IVJ controls");

            //add the actual buttons
            container.prepend($('<div class="ivj-controls"></div>')
                .append(
                    $('<a href=""><img class="icon" src="'+this.settings.path+'resources/play.gif"></a>')
                        .click((function(self){return function(){if(self.script == null) self.script = ivj_script.default_scripts.orbit;self.run_script();return false;}})(this)))
                .append(
                    $('<a href=""><img class="icon" src="'+this.settings.path+'resources/pause.gif"></a>')
                        .click((function(self){return function(){self.pause();return false;}})(this)))
                .append(
                    $('<a href=""><img class="icon rightside" src="'+this.settings.path+'resources/fullscreen.gif"></a>')
                        .click((function(self){return function(){self.appletFullscreen();return false}})(this)))
                .append(
                    $('<a href=""><img class="icon rightside" src="'+this.settings.path+'resources/globe.gif"></a>')
                        .click((function(self){return function(){self.go_to('goto;0;0;30000000');return false;}})(this))
                )
            );
        }
        $('body').append(container)

        //set up a timer to check that we have loaded after 60 seconds.
        this.loading_timer = setTimeout((function(self){
            return function(){
                if(!self.loaded)
                {
                    message = $('<span>'+_('Still loading? If you are on a slow connection or this is your first visit this is probably normal.')+'</span>')
                        .append(self.message_button(_('Dismiss'),'dismiss'))
                        .append(self.message_button(_('Test System'),'retest'));
                    $.bar({message:message,click_to_close:false});
                    $.log("Displaying loading time message");
                }
            }
        })(this),60000);

        //poll firefox
        if(/Mac/.test(navigator.platform) && $.browser.mozilla)
        {
            this.poll();
        }
    }
    catch(err)
    {
        $.log(err);
    }
}

/**
* @description Include IVJ applet, check java version, and manage applet
* javascript communication.
*
* @constructor
* @param input_placeholder - string ID of the placeholder element on the page.
* @param input_settings - settings for the IVJ instance
*/
function ivj(input_placeholder, input_settings)
{
    //Properties: Page Elements
    this.object = null;         //the applet
    this.placeholder = null;    //the div on the page where the applet will go.

    //Properties: Positioning
    this.offset = null;
    this.width = 0;
    this.height = 0;
    this.scroll_y = 0;

    //Properties: Animation
    this.script = null;

    //Properties: State
    this.settings = null;
    this.full_screen = false;
    this.loaded = false;
    this.environment=false;
    this.tag=false;
    this.cookie = false;
    this.loc=null;

    try
    {
        $.debug_state(true);
        $.log('Method: constructor');

        //Validate: Make sure we have placeholder element
        this.placeholder = $('#'+input_placeholder);
        if(!this.placeholder.length)
            throw _('error_no_placeholder');

        //Setup: Get all settings.
        this.settings = $.extend({
            'id':null,
            'allow_full_screen': true,
            'auth_token':null,
            'group_id':null,
            'startup_action':'none',
            'startup_location':null,
            'startup_script':null,
            'show_side_panel':true,
            'path':'',
            'click_to_start':false,
            'lang':'en',
            'use_cookies':true,
            'controls':true,
            'hierarchy':''
        },input_settings);

        //Setup: get ID
        if(this.settings.id == null)
            throw _("Error: No ID specified.")

        //add to static instances so we can reference it later
        ivj.instances[this.settings.id] = this;

        //add startup script if defined
        if(this.settings.startup_script)
            this.script = this.settings.startup_script;

        //get position info
        this.get_position();

        //bind resizing events
        var position_closure = function(self){
            return function(){
                self.position();
            }
        };
        $(window).resize(position_closure(this));
        $(window).load(position_closure(this));

        //determine java status
        var load = true;
        var message = '';
        this.cookie = $.cookie('ivj_tag') || {tag:null,status:'unknown',version:null}; //tag:activex:object:applet status:ok:retesting:upgrading:unknown
        $.log(this.cookie);

        //if there is a cookie message, display it
        if($.cookie('ivj_message'))
        {
            $.bar({message:$.cookie('ivj_message')});
            $.cookie('ivj_message',null);
            load = false;
        }
        else if(this.cookie.status != 'ok')
        {
            //if doing the complete test, show a message
            if(this.cookie.status=='retesting')
            {
                $.bar({message:_('Performing a full test of your system.'),click_to_close:true});
            }

            //Either no cookie was set, or the user just installed a java upgrade.
            //we are not sure which, but either way we need to test their system.
            if(this.env(this.cookie.status=='retesting').passed)
            {
                if(this.cookie.status=='retesting')
                {
                    //if this was a retest, display a messaage
                    message = $('<span>'+_('No problems found.')+'&nbsp&nbsp</span>')
                        .append(this.message_button(_('Load InteleView'),'ivj'));
                    $.bar({message:message,click_to_close:false});
                    load = false;
                }
            }
            else if(this.env().tag !== false)
            {
                /**
                 * We know our tag will work, but scripting seems to be disabled.
                 * Show a warning message but allow IVJ to load ing the background.
                 * Also offer the full test.
                 */
                if(this.cookie.status=='retesting')
                {
                    message = $('<span>'+_('There appears to be a problem communicating with Java on your system. This could be caused by an outdated version of the java plugin, or if you are running your system in a secured environment. Inteleview will run, but some features such as viewing scripts and using full screen mode will be unavailable.')+'<br></span>')
                        .append(this.message_button(_('Load InteleView'),'ivj'));
                    load = false;
                }
                else
                {
                    message = $('<span>'+_('Unable to communicate with Java. InteleView will load, but some features may be disabled.')+'&nbsp;&nbsp;</span>')
                        .append(this.message_button(_('Test System (Cancels Loading)'),'retest'));
                }
                message.append(this.message_button(_('Dismiss'),'dismiss'));
                $.bar({message:message,click_to_close:false});
            }
            else if(this.env().version_check == -0.2)
            {
                /**
                 * Java is installed, but not enabled. We can detect this only in
                 * non-IE browsers. Ask them to enable it and reload the page. Also
                 * offer the full test.
                 */
                if(this.cookie.status=='retesting')
                {
                    message = $('<span>'+_('Java has been detected on your system, but it appears to be disabled. In your browsers preferences or options, you shuld ensure that the item labeled "Enable Java" is checked. Detailed instructions for <a href="http://support.mozilla.com/en-US/kb/Using+the+Java+plugin+with+Firefox#Enabling_Java">Firefox</a>, <a href="http://docs.info.apple.com/article.html?path=Safari/3.0/en/9279.html">Safari</a>. After you have enabled Java, reload this page.')+'<br></span>');
                }
                else
                {
                    message = $('<span>'+_('Disabled Java detected. Please enable it in your browser preferences and reload.')+'&nbsp;&nbsp;</span>')
                        .append(this.message_button(_('Test System'),'retest'));
                }
                message.append(this.message_button(_('Reload'),'reload'));
                $.bar({message:message,click_to_close:false});
                load = false;
            }
            else if(this.cookie.status=='upgrading')
            {
                /**
                 * The cookie says they at least clicked the upgrade button, but
                 * we still can't find a usable version of java. Offer upgrade button
                 * again and the full test.
                 */
                message = $('<span>'+_('Java upgrade detected, but unable to find compatible version.')+'&nbsp;&nbsp;</span>')
                    .append(this.message_button(_('Try Upgrade Again'),'upgrade'))
                    .append(this.message_button(_('Test System'),'retest'));
                $.bar({message:message,click_to_close:false});
                load = false;
            }
            else
            {
                /**
                 * No java found. Offer the option to upgrade, or not.
                 */
                if(this.cookie.status=='retesting')
                {
                    if(this.env().platform.mac)
                    {
                        message = $('<span>'+_('The full system test was not able to detect a compatible version of Java on your system. If you have not yet attempted to upgrade your java plugin that may fix the problem. If you are running a 32 bit Intel Mac, such as an older Mac Book Pro, your machine may not be capable of running the required version of Java.')+'<br></span>');
                    }
                    else
                    {
                        message = $('<span>'+_('The full system test was not able to detect a compatible version of Java on your system. If you have not yet attempted to upgrade your java plugin that may fix the problem.')+'<br></span>');
                    }
                }
                else
                {
                    message = $('<span>'+_('We were unable to detect a compatible version of Java. Would you like to upgrade?')+'&nbsp;&nbsp;</span>');
                }
                message.append(this.message_button(_('Upgrade Now!'),'upgrade'))
                    .append(this.message_button(_('Dismiss'),'dismiss'));
                $.bar({message:message,click_to_close:false});
                load = false;
            }
        }

        //add reporting button
        if(message!=''&&this.cookie.status=='retesting')
        {
            message.append(this.message_report());
        }

        //Add applet and remember tag for next time.
        if(load)
        {
            if(this.settings.click_to_start)
            {
                this.click_to_start();
            }
            else
            {
                if(this.cookie.status != 'ok')
                {
                    this.tag = this.env().tag
                    $.cookie('ivj_tag',{tag:this.tag,status:'ok',version:0},365);
                }
                else
                {
                    this.tag = this.cookie.tag;
                }
                this.add_applet();
            }
        }
    }
    catch(err)
    {
        $.log(err);
    }
}

ivj.prototype.message_button = function(message,action)
{
    return $('<a class="btn" href="">'+message+'</a>').click(this.button_actions[action](this));
}

ivj.prototype.poll = function()
{
    $.log("Method: poll")
    try
    {
        if(this.instance().getOrbitView().getZoom())
        {
            this.appletInit();
            setTimeout((function(self){return function(){self.appletStart()}})(this),2000);
        }
    }
    catch(err)
    {
        //setup next call
        setTimeout((function(self){return function(){self.poll()}})(this),1000);
    }
}

ivj.prototype.message_report = function()
{
    return $('<a class="btn" href="">'+_('Report Problem')+'</a>').click(function(){
        var buttons = $('.btn').not(this);
        $('body').append(buttons);
        $('.jbar-content').empty()
            .append($([
                '<form id="ivj-report" style="padding:0;margin:0" method="post" action="'+ivj.problem_post_url+'"><p><label for="ivj-report-message">',
                    _('Please describe the problem (Details of your system, such as browser and java version, will be submitted with your report.)'),
                '</label><br><textarea name="ivj-report-message" id="ivj-report-message" ></textarea></p>',
                '<p><label for="ivj-report-email">'+_('Email (optional)')+':</label> <input name="ivj-report-email" id="ivj-report-email" type="text"></p>',
                '<input type="hidden" name="system" value="'+navigator.platform+'">',
                '<input type="hidden" name="browser" value="'+navigator.userAgent+'">',
                '<input type="hidden" name="java_version_check" value="'+ivj.env.version_check+'">',
                '<input type="hidden" name="java_tag" value="'+ivj.env.tag+'">',
                '<input type="hidden" name="java_description" value="'+ivj.env.java_info.description+'"></form>'

            ].join('')))
            .append($('<a class="btn" href="">'+_('Submit Report')+'</a>').click(function(){
                $.cookie('ivj_message',_('Your issue has been submitted and we are looking for a solution now.'));
                $('#ivj-report').submit();
                return false;
            }))
            .append(buttons);
        return false;
    });
}

ivj.prototype.button_actions = {
    'upgrade':function(self){return function(){self.upgrade();return false;}},
    'dismiss':function(self){return function(){$.removebar();return false;}},
    'reload':function(self){return function(){location.reload(true);return false;}},
    'ivj':function(self){return function(){$.removebar();self.tag=self.env().tag;$.cookie('ivj_tag',{tag:self.tag,status:'ok',version:0},365);self.add_applet();return false;}},
    'retest':function(self){return function(){$.cookie('ivj_tag',$.extend(self.cookie,{status:'retesting'}));location.reload(true);return false;}}
}

/**
 *code and archive are both attributes
 */
ivj.get_applet_tag = function(attr,params)
{
    return [
        '<applet mayscript="true" ' + ivj.get_attributes(attr) + '>',
        '<param name="mayscript" value="true" />',
        ivj.get_params(params),
        '</applet>'
    ].join('');
}

/**
 * code is prefixed by java: and moved to and attribute named classid
 * archive is both a param and and attribute
 */
ivj.get_object_tag = function(attr,params)
{
    if(typeof(attr['code'])!='undefined')
    {
        attr['classid'] = 'java:' + attr['code'];
        delete attr['code'];
    }
    if(typeof(attr['archive'])!='undefined')
    {
        params['archive'] = attr['archive'];
    }
    return [
        '<object type="application/x-java-applet" ' + ivj.get_attributes(attr) + '>',
        '<param name="mayscript" value="true" />',
        '<param name="scriptable" value="true" />',
        ivj.get_params(params),
        '</object>'
    ].join('');
}

/**
 *code is a param, archive is a param
 */
ivj.get_activex_tag = function(attr,params)
{
    if(typeof(attr['code'])!='undefined')
    {
        params['code'] = attr['code'];
        delete attr['code'];
    }
    if(typeof(attr['archive'])!='undefined')
    {
        params['archive'] = attr['archive'];
        delete attr['archive'];
    }
    return [
        '<object classid="clsid:8AD9C840-044E-11D1-B3E9-00805F499D93" ' + ivj.get_attributes(attr) + '>',
        '<param name="mayscript" value="true" />',
        '<param name="scriptable" value="true" />',
        ivj.get_params(params),
        '</object>'
    ].join('');
}

/**
 *
 */
ivj.get_attributes = function(attr)
{
    var ret = '';
    for(i in attr)
    {
        ret += i + '="' + attr[i] + '" ';
    }
    return ret;
}

/**
 *
 */
ivj.get_params = function(params)
{
    var ret = '';
    for(i in params)
    {
        ret += "<param name=" + i + " value='" + params[i] + "'>"
    }
    return ret;
}

ivj.prototype.upgrade = function()
{
    $.cookie('ivj_tag',$.extend(this.cookie,{status:'upgrading'}));
    location.href = 'http://java.sun.com/webapps/getjava/BrowserRedirect?host=java.com&returnPage='
        + document.location;

}

ivj.prototype.click_to_start = function()
{
    this.placeholder.click(
        (function(self){return function(){self.add_applet();}})(this)
    ).css('cursor','pointer').find('.ivj-placeholder-text').text(_('Click to start InteleView'));
}

/**
 * Run the java and browser detection.
 *
 * @method
 * @param <boolean>
 * @return <int>
 */
ivj.prototype.env = function(retest)
{
    //set defaults
    if(typeof(retest)=='undefined') retest = false;

    //only test the first time
    if(ivj.env == false || retest)
    {
        $.log("Method: env (check java and browser)");

        ivj.env = {
            'java_info':false,
            'passed':false,
            'tag':false,
            'version_check':false,
            'platform':{'win':false,'mac':false,'linux':false},
            'browser':$.browser
        };

        //Do java detection. If this is a retest, use the applet methods
        var mode = retest ? 3 : 2;
        var verify_tags = ivj.env.browser.msie ? [0,mode,mode] : [mode,mode,0];
        var info = ivj.env.java_info = PluginDetect.getInfo(
            'Java',
            this.settings.path + 'resources/getJavaInfo.jar',
            verify_tags
        );

        //verify minimum version
        ivj.env.version_check = PluginDetect.isMinVersion('Java', '1,6,0,0');

        //determine tag to use. If this is the
        if(ivj.env.version_check === 1)
        {
            if(ivj.env.browser.msie)
            {
                if(info.objectTagActiveX==null&&info.appletTag==null&&!retest)
                {
                    //no applet methods were used and we are not doing a retest
                    ivj.env.tag = 'activex';
                    ivj.env.passed = true;
                }
                else if(info.objectTagActiveX===1)
                {
                    ivj.env.tag = 'activex';
                    ivj.env.passed = true;
                }
                else if(info.appletTag===1)
                {
                    ivj.env.tag = 'applet';
                    ivj.env.passed = true;
                }
                else if(info.objectTagActiveX===0)
                {
                    ivj.env.tag = 'activex';
                    ivj.env.passed = false;
                }
                else if(info.appletTag===0)
                {
                    ivj.env.tag = 'applet';
                    ivj.env.passed = true;
                }
            }
            else
            {
                if(info.objectTag==null&&info.appletTag==null&&!retest)
                {
                    //no applet methods were used and we are not doing a retest
                    ivj.env.tag = 'object';
                    ivj.env.passed = true;
                }
                if(info.objectTag===1)
                {
                    ivj.env.tag = 'object';
                    ivj.env.passed = true;
                }
                else if(info.appletTag===1)
                {
                    ivj.env.tag = 'applet';
                    ivj.env.passed = true;
                }
                else if(info.objectTag===0)
                {
                    ivj.env.tag = 'object';
                    ivj.env.passed = false;
                }
                else if(info.appletTag===0)
                {
                    ivj.env.tag = 'applet';
                    ivj.env.passed = true;
                }
            }
        }

        //platform (simple check)
        if(/Win/.test(navigator.platform)) ivj.env.platform.win = true;
        else if(/Mac/.test(navigator.platform)) ivj.env.platform.mac = true;
        else if(/Linux/.test(navigator.platform)) ivj.env.platform.linux = true;

        $.log(ivj.env);
    }
    return ivj.env;
}

ivj.prototype.get_tag = function(attr,params)
{
    if(this.tag=='object') return ivj.get_object_tag(attr,params);
    else if(this.tag=='activex') return ivj.get_activex_tag(attr,params);
    else if(this.tag=='applet') return ivj.get_applet_tag(attr,params);
}

/**
 * Get the current position of the placeholder
 */
ivj.prototype.get_position = function()
{
    this.offset = this.placeholder.offset();
    this.width = this.placeholder.width();
    this.height = this.placeholder.height();
}

/**
* Set the applet position based on fullscreen mode and placeholder position
*
* @method
* @return void
*/
ivj.prototype.position = function()
{
    $.log("Method: position");

    var offset = this.settings.controls ? 20 : 0;
    var element = $('#'+this.settings.id+'-container');

    if (this.full_screen)
    {
        //remove information bars - they'll just get int he way
        $.removebar();

        //Add at the current scroll location (+1 for when we scroll below)
        this.scroll_y = $(window).scrollTop();
        element.height($(window).height()).width($('body').width()).css({
            top: (this.scroll_y+1)+'px',
            left: 0
        }).find('#'+this.settings.id).height($(window).height()-offset);

        //scroll hack to force a redraw
        window.scroll(0,this.scroll_y+1);
    }
    else
    {
        this.get_position();
        element.width(this.width).height(this.height).css({
            top:this.offset.top + 'px',
            left:this.offset.left + 'px'
        }).find('#'+this.settings.id).height(this.height-offset);
    }
}

/**
 * Get the current instance of the IVJ object, eithe rold style or new style.
 *
 * @method
 * @return {object}
 */
ivj.prototype.instance = function()
{
    var theApplet = this.object[0];
    try
    {
        theApplet = theApplet.getSubApplet();
    }
    catch (e)
    {

    }
    return theApplet;
}

/**
* Applet is initialized
*
* @method
* @return void
*/
ivj.prototype.appletInit = function()
{
    $.log('Method: appletInit');

    //turn on full screen interface elements if requested
    if (this.settings.allow_full_screen)
    {
        this.toggle_full_screen();
    }
};

/**
* Globe has rendered
*
* @method
* @return void
*/
ivj.prototype.appletStart = function()
{
    $.log('Method: appletStart');
    this.loaded = true;
    this.position();
};

/**
* Applet is exiting
*
* @method
* @return void
*/
ivj.prototype.appletStop = function()
{
    $.log('Method: appletStop');
};

/**
* Applet is signaling full screen
*
* @method
* @param {Bool} state: the desired full screen state
* @return void
*/
ivj.prototype.appletFullscreen = function(state)
{
    $.log('Method: appletFullscreen');

    //continue only if full screen mode is allowed
    if (this.settings.allow_full_screen && state !== this.full_screen)
    {
        if (state==false || (typeof state == 'undefined' && this.full_screen))
        {
            this.full_screen = false;
            this.position();
        }
        else
        {
            $("body", "html").css({
                height: "100%",
                width: "100%"
            });
            this.full_screen = true;
            this.position();
        }
    }
};

/**
* Direct the applet to a new location
*
* @method
* @param {string} string_coordinates
* @return void
*/
ivj.prototype.go_to = function(string_coordinates)
{
    $.log('Method: go_to');

    //send correct method signature depending on params going out
    var params = string_coordinates.split(';');
    if(params.length == 3)
        this.instance().gotoLatLon(
            parseFloat(params[1]),
            parseFloat(params[2])
            );
    else if(params.length == 4)
        this.instance().gotoLatLon(
            parseFloat(params[1]),
            parseFloat(params[2]),
            parseFloat(params[3]),0,0
            );
    else if(params.length == 5)
        this.instance().gotoLatLon(
            parseFloat(params[1]),
            parseFloat(params[2]),
            parseFloat(params[3]),
            parseFloat(params[4]),0
            );
    else if(params.length == 6)
        this.instance().gotoLatLon(
            parseFloat(params[1]),
            parseFloat(params[2]),
            parseFloat(params[3]),
            parseFloat(params[4]),
            parseFloat(params[5])
            );
};

/**
* Toggle the applet full screen awareness state
*
* @method
* @return void
*/
ivj.prototype.toggle_full_screen = function()
{
    $.log('Method: toggle_full_screen');
    this.instance().toggleFullscreenMode();
}

/**
* Creates or updates a screen overlay
*
* @method
* @return void
*/
ivj.prototype.screen_overlay = function(id,name,description,url,x,y,opacity,corner_radius)
{
    $.log('Method: screen_overlay');

    //check required params
    if(!name || !url) return false;

    //prepare optional params
    corner_radius = corner_radius || 0;
    opacity = opacity || 1;
    x = x || 0;
    y = y || 0;
    description = description || '';
    id = id || ivj.generate_id();
    $.log(id+', name:'+name+', desc:'+description+', url:'+url+', x:'+x+', y:'+y+', a:'+opacity+', corner:'+corner_radius);

    //switch action based on ID
    if(this.overlays.toString().indexOf(id) === -1)
    {
        this.instance().addScreenOverlay(
            id, name, description, url, x, y, opacity, true, corner_radius);
        this.overlays.push(id);
    }
    else
    {
        this.instance().refreshScreenOverlay(
            id, name, description, url, x, y, opacity, true, corner_radius);
    }

    //return ID
    return id;
}

/**
* Set the opacity of the layer with the provided ID
*
* @method
* @return boolean
*/
ivj.prototype.set_layer_opacity = function(id,opacity)
{
    $.log('Method: set_layer_opacity');

    //validate inputs
    if(!id || !opacity) return false;

    //direct traffic
    if(this.overlays.toString().indexOf(id) > -1)
    {
        return this.instance().setLayerOpacityById(id, opacity)
    }
    else
    {
        return this.instance().setLayerOpacityByDatabaseId(id, opacity)
    }
};

/**
* Set the visibility of the layer with the provided ID
*
* @method
* @return string
*/
ivj.prototype.set_layer_visibility = function(id,state)
{
    $.log('Method: set_layer_visibility');

    //validate inputs
    if(!id || !state) return false;

    //direct traffic
    if(this.overlays.toString().indexOf(id) > -1)
    {
        return this.instance().setLayerEnabledById(id, state)
    }
    else
    {
        return this.instance().setLayerEnabledByDatabaseId(id, state)
    }
};

/**
* Get the current coordinates
*
* @method
* @return string
*/
ivj.prototype.get_coordinates = function()
{
    $.log('Method: get_coordinates');

    //get coordinates
    var lat = Math.round(this.instance().getOrbitView().getCenterPosition().getLatitude().degrees*1000000)/1000000;
    var lon = Math.round(this.instance().getOrbitView().getCenterPosition().getLongitude().degrees*1000000)/1000000;
    var zoom = Math.round(this.instance().getOrbitView().getZoom());
    var head = Math.round(this.instance().getOrbitView().getHeading().degrees*100)/100;
    var pitch = Math.round(this.instance().getOrbitView().getPitch().degrees*100)/100;
    return 'Coordinates' + ';' + lat + ';' + lon + ';' + zoom + ';' + head + ';' + pitch;
};

/**
* Load a KML file
*
* @method
* @return void
*/
ivj.prototype.load_kml = function(name,uri)
{
    $.log('Method: load_kml');
    this.instance().addKmlLayer(name,uri);
};

/**
 *Run a script made up of multiple goto locations
 *
 *@method
 *@return void
 */
ivj.prototype.run_script = function()
{
    if(this.script)
    {
        this.script.play(this.settings.id,true);
    }
}

/**
 *Load a script into an array for running
 *
 *@method
 *@return void
 */
ivj.prototype.load_script = function(object_script)
{
    this.script = object_script;
}

/**
 *Pause a script
 *
 *@method
 *@return void
 */
ivj.prototype.pause = function()
{
    if(this.script)
    {
        this.script.pause(this.settings.id);
    }
}

/**
 *Load a script into an array for running
 *
 *@method
 *@return void
 */
ivj.prototype.load_script_from_string = function(string_script)
{
    this.script = new ivj_script(this.settings.id,string_script);
}

/**
 * Static Properties
 */
ivj.instances = {};
ivj.deployment_toolkit=null;
ivj.env = false;
