// prototype functions needed for basic js needs

String.prototype.endsWith = function(suffix) {
    return this.indexOf(suffix, this.length - suffix.length) !== -1;
};

if (typeof String.prototype.startsWith != 'function') {
    // see below for better implementation!
    String.prototype.startsWith = function (str) {
        return this.indexOf(str) == 0;
    };
}


/**
* Keeps all messages used in the framework. It can be used later to translate the application 
*/
var StringMsgs = {

    /**
    * Common string messages used in the application
    */
    Common : {
        ContactingServer: "Contacting server. Please wait...",
        Loading: "Loading ",
        Error: "Error",
        Successful: "Successful",
        Message: "Message"
    },

    /**
    * String messages used by framework only 
    */
    Framework: {
        ConfirmDelete_DialogTitle: "Delete Item",
        ConfirmDelete_Msg: "You are about to delete something. Are you sure?",
        EditForm_FormDataNotValid: "Form data is not valid. Please revise the form again before submit.",
        EditForm_SaveSuccessful: "Information Saved successfully.",
        EditForm_PasswordNotMatch: "Entered password and verify password should be the same.",
        RegisterForm_PleaseAgreeTermAndConditions: "Please agree terms and conditions to continue.",
        Grid_SelectOneRow: "No item is selected. Please select a row first.",
        General_OperationDoneSuccessfully: "Operation completed successfully.",

    }



};


/**
* Utility functions to manage basic functions of the framework
*/
var Framework = {

    /**
    * gets a value from query string
    */
    getQueryString: function (urlVarName) {
        var urlHalves = String(document.location).split('?');
        var urlVarValue = '';
        if (urlHalves[1]) { var urlVars = urlHalves[1].split('&'); for (i = 0; i <= (urlVars.length); i++) { if (urlVars[i]) { var urlVarPair = urlVars[i].split('='); if (urlVarPair[0] && urlVarPair[1] && urlVarPair[0] == urlVarName) { urlVarValue = urlVarPair[1]; } } } }
        return urlVarValue;
    },

    addQueryString: function (url, pName, pValue) {
        if (pValue) {
            if (url.indexOf('?') > 0)
                return url + "&" + pName + "=" + pValue;
            else
                return url + "?" + pName + "=" + pValue;
        }
        else
            return url;
    },

    /**
    * finds the main window of the application recursively
    */
    getMainWindow: function() {

        var win = window;

        if (win.MainPageSignatureXWZ !== undefined)
            return win;
        if (win.parent.MainPageSignatureXWZ !== undefined)
            return win.parent;

        else {
            for (var i = 0; i <= 10; i++) {
                win = win["parent"];
                if (win.MainPageSignatureXWZ !== undefined)
                    return win;
            }
        }

        return win;
    },


    /**
    * Asks user to confirm deleting an item before delete
    */
    confirmDelete: function (deleteFunction, returnControl) {

        var msgSettings = {
            title: StringMsgs.Framework.ConfirmDelete_DialogTitle,
            msg: StringMsgs.Framework.ConfirmDelete_Msg,
            buttons: Ext.Msg.YESNO,
            fn: function (btn) {
                if (btn == 'yes')
                    deleteFunction();
                if (returnControl) // focus for the control after execution
                    if (returnControl.focus !== undefined)
                        returnControl.focus();
            }
        }

        if (returnControl)
            msgSettings.animEl = returnControl.id;

        return Ext.Msg.show(msgSettings);
    },

    /*
      Converts path started with ~/Path to path accessible form client
      WARNING: use this function in the same window that you need to access resource
      otherwise it resolves url for the window that you called it from
    */
    resolveClientUrl: function (url) {
        if (url.startsWith("~/") == false)
            return url;
        var baseUrl = Framework.privateGetBaseClientPath();
        return Framework.concatUrl(baseUrl, url.substr(2, url.length - 2));
    },

    concatUrl: function(url1, url2) {
        if (url1.endsWith('/') == true)
            return url1 + url2;
        else
            return url1 + "/" + url2;
    },

    privateGetBaseClientPath: function() {
        var currentjsPath = "fw/js/common.js"; // if function moved to another file, this needs to be updated
        // since framework common.js is one of the scripts in the document
        // we search all scripts and by removing the path, we get the root
        if (window.privateBaseClientPath)
            return window.privateBaseClientPath;
        else
        {
            var scripts = document.getElementsByTagName("script");
            for (var i = 0; i < scripts.length; i++)
            {
                src = scripts[i].src.toLowerCase();
                if (src.indexOf(currentjsPath) > -1)
                {
                    window.privateBaseClientPath = src.replace(currentjsPath, "");
                    return window.privateBaseClientPath;
                }
            }
        }
    },

    /**
     * Returns a random integer between min and max
     * Using Math.round() will give you a non-uniform distribution!
     */
    getRandomInt: function (min, max) {
        return Math.floor(Math.random() * (max - min + 1)) + min;
    },

    /*
      redirects the selected page to the selected url
    */
    redirectTo: function (newUrl, win) {
        newUrl = Framework.resolveClientUrl(newUrl);
        win.location.href = newUrl;
    },

    /* clicks on a button */
    buttonClick: function (btn) {
        btn.btnEl.dom.click();
        //btn.fireEvent('click', btn);
        //btn.handler.call(btn.scope, btn, Ext.EventObject);
    },


}
