﻿/*
    MIT License

    Copyright (c) 2009 Mats Bryntse

    Permission is hereby granted, free of charge, to any person obtaining a copy
    of this software and associated documentation files (the "Software"), to deal
    in the Software without restriction, including without limitation the rights
    to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
    copies of the Software, and to permit persons to whom the Software is
    furnished to do so, subject to the following conditions:

    The above copyright notice and this permission notice shall be included in
    all copies or substantial portions of the Software.

    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
    AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
    OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
    THE SOFTWARE.
*/

/* 
    Globals.IframeScanner
    This class object holds 2 iframes and compare properties between them after a script has been loaded
*/ 

Ext.ns('Globals');

Globals.IframeScanner = function (){
    function createFrame () {
        var frame = Ext.DomHelper.append(Ext.getBody(), { tag : "iframe" });
        frame.frameBorder = '0';
        frame.className = 'x-hidden';
        return frame;
    }
    
    this.freshFrame = createFrame();
    
    this.scriptHostFrame = createFrame();
    
    // Keep a reference to each of the window objects
    this.freshWin = window.frames[0].window;
    this.scriptHostWin = window.frames[1].window;
};

Ext.apply(Globals.IframeScanner.prototype, {

    // Set src of the script hosting iframe to an asp that just includes the files passed in arg1 and arg2
    loadScripts: function(scriptUrls, cssUrls, callback, callbackScope, callbackArgument) {
        var allFiles = scriptUrls.concat(cssUrls || []);
        this.scriptHostFrame.setAttribute("src", "host.asp?files=" + encodeURIComponent(allFiles.join(',')));

        var that = this;
        this.scriptHostFrame[Ext.isIE ? "onreadystatechange" : "onload"] = function() {
            if (!Ext.isIE || that.scriptHostFrame.readyState === "complete") {
                startScan.call(that);
            }
        };

        function startScan() {
            var globals = [];

            // Check for native class augmentations
            Ext.each(Globals.nativeSymbols, function(item) {

                try {
                    if (typeof (this.scriptHostWin[item]) !== 'undefined') {
                        // Static properties
                        var staticDiff = this.getObjectDifferences(this.freshWin[item],
                                                                   this.scriptHostWin[item],
                                                                   item === 'window' ? "" : item + '.',
                                                                   item === 'window' ? "Global symbols" : "Native class augmentations");
                        globals.push.apply(globals, staticDiff);

                        // Prototype properties
                        if (this.scriptHostWin[item].prototype) {
                            var prototypeDiff = this.getObjectDifferences(this.freshWin[item].prototype,
                                                                          this.scriptHostWin[item].prototype,
                                                                          item + '.prototype.',
                                                                          "Native class augmentations");
                            globals.push.apply(globals, prototypeDiff);
                        }
                    }
                } catch (e) {
                    // IE crashes here
                }

            }, this);

            var sheetColl;

            try {
                sheetColl = this.scriptHostWin.document.styleSheets;
                Ext.each(sheetColl, function(sheet) {
                    Ext.each(sheet.cssRules, function(rule) {
                        globals.push({
                            name: rule.selectorText,
                            value: rule.cssText,
                            category: 'CSS style rules'
                        });
                    });
                });
            } catch (e) {
                // Possibly a security exception 
            }
            callback.call(callbackScope, that, globals, callbackArgument);
        }
    },

    getObjectDifferences: function(cleanObj, dirtyObj, namePrefix, category) {
        var diff = [];

        for (var p in dirtyObj) {
            try {
                if (dirtyObj.hasOwnProperty(p)) {
                    var fullName = namePrefix + p;

                    // Check if the object exists on the clean window and also do a string comparison
                    // in case a builtin method has been overridden
                    if ((typeof (cleanObj[p]) == 'undefined' ||
                        (typeof (dirtyObj[p]) == 'function' && cleanObj[p].toString() !== dirtyObj[p].toString())) &&
                        Array.indexOf(Globals.excludeProperties, fullName) < 0) {

                        var val;
                        var overriddenNative = cleanObj[p] && (typeof (dirtyObj[p]) == 'function' && cleanObj[p].toString() !== dirtyObj[p].toString());

                        switch (typeof (dirtyObj[p])) {
                            case 'object':
                            case 'function':
                                if (dirtyObj[p] && dirtyObj[p].toString) {
                                    val = dirtyObj[p].toString();
                                } else {
                                    val = dirtyObj[p];
                                }
                                break;

                            default:
                                val = dirtyObj[p];
                                break;
                        }

                        diff.push({
                            name: namePrefix + p,
                            type: typeof (dirtyObj[p]),
                            value: val,
                            category: overriddenNative ? "Overriden native function" : category
                        });
                    }
                }
            } catch (e) {
                // Just continue
            }
        }

        return diff;
    },

    runJsLint: function(urlsArray, cb) {

        var errors = [];
        var totalText = '';

        var i = 0;

        function callServer() {
            Ext.Ajax.request({
                url: urlsArray[i],
                method: 'GET',
                callback: function(options, success, response) {
                    if (response) {
                        totalText = totalText + ' ' + response.responseText;
                        i = i + 1;
                        if (i < urlsArray.length) {
                            callServer.call(this);
                        } else {
                            JSLINT(totalText, {
                                browser: true
                            });
                            Ext.Msg.alert('er', JSLINT.report(false));
                            cb.call(this, JSLINT.getImpliedGlobals());
                        }
                    }
                },
                scope: this
            });
        }

        callServer.call(this);
    }
});

// Array.indexOf doesn't exist in Chrome
if (!Array.indexOf) {
    Array.indexOf = function(array, obj) {
        var retVal = -1;
        
        Ext.each(array, function(item, index) {
            if (item === obj) {
                retVal = index;
                return false;
            }
        });
        
        return retVal;
    };
}