/// Declare Namespace

TVI = { version: "0.2" };

// Create function for applying config options to classes
TVI.apply = function(o, c, d){

    // o = object   : The object that is having stuff applied to it.
    // c = config   : The config options that will be applied to the object
    // d = defaults : Any default options that
    
    // See if defaults have been supplied
    if (d) {
        // If they have then call the apply function again with the defaults as the config
        TVI.apply(o, d);
    }

    // Check the object and config are valid objects
    if (o && c && typeof c == 'object') {
        // Loop through the config and add all the properties and methods
        for (var p in c) {
			// Check that we're only dealing with config members, not stuff inherited through the prototype
            if (c.hasOwnProperty(p) && c[p] !== undefined) {
		        o[p] = c[p];
		    }
        }
    }
	
    // Return the original object
    return o;
};


// Closed function - is not global but is instantiated and run immediately
(function() {

    // ********** Set up TVI variable and methods ********** //

    TVI.apply(TVI, {

        /**
        * Counter for creating uniqu ID's for components.
        * @property
        * @type integer
        */
        idSeed: 0,

        /**
        * Function for creating a unique ID for any control
        * @property
        * @type Function
        */
        createID: function(o, prefix) {
            prefix = prefix || "TVI-auto-";
            if (o.id === undefined || o.id === null || o.id === '') {
                var id = prefix + (++this.idSeed);
                o.id = id;
            }
            return o;
        },

        /**
        * A reusable empty function
        * @property
        * @type Function
        */
        emptyFn: function() { },

        /**
        * List of field types used in forms
        * @property
        * @type Array
        */
        fieldTypes: [
		        'textBox',
		        'textArea',
		        'dropDownList',
		        'checkBox',
			    'password',
			    'multiRadio',
			    'multiCheckBox'
		    ],

        /**
        * List of allowed data types when communicating with a database
        * @property
        * @type Array
        */
        dataTypes: [
			    'varchar',
			    'text',
			    'boolean',
			    'integer',
			    'decimal',
			    'date'
		    ],

        /**
        * Ajax - wraps up the jQuery Ajax function and adds defaults
        */
        ajax: function(params) {

            // Defaults for ajax calls
            var defaults = {
                type: 'POST',
                contentType: 'application/json; charset=utf-8',
                dataType: 'json',
                data: '{}'
            };

            var successFunction = params.success;
            var failureFunction = params.failure;

            // Overwrite the default parameters with the ones passed in
            var ajaxParams = TVI.apply(defaults, params);

            // Intercept the success function and add some functionality
            ajaxParams.success = function(data) {

                // Parse the response
                var response = JSON.parse(data.d);

                // Check that the call was successful
                if (response.success === true) {

                    // Run the success function if it exists
                    if (successFunction) {
                        successFunction.call(this, response);
                    }
                }
                else {
                    // Run the failure function if it exists
                    TVI.logError(response);
                    if (failureFunction) {
                        failureFunction.call(this, response);
                    }
                }

            };

            // Intercept the error function and pass it through to the default ajax error function.
            ajaxParams.error = function() {

                var errorCode = params.errorCode || '010004';
                var errorMessage = params.errorMessage || 'Error occured during Ajax call';

                // Log the error to the console
                TVI.logError({
                    "code": errorCode,
                    "message": errorMessage
                });

                // Run the error function if it exists
                if (params.error !== undefined && params.error !== null) {
                    params.error.call();
                }
            };

            // Make the ajax call
            $.ajax(ajaxParams);

        },

        /**
        * Check to see if the Firebug console exists for error logging
        */
        firebugCheck: function() {

            // Attempt top initialise the console if it doesn't exist
            if (typeof console == 'undefined') {
                if (typeof loadFirebugConsole == 'function') {
                    loadFirebugConsole();
                }
            }

            // Now check to see if the console exists
            if ($.browser.mozilla && window.console !== null && window.console !== undefined) {
                return true;
            }
            else {
                return false;
            }
        },

        /**
        * Log an error to the Firebug console.
        * @param {Object} errorObject - An object containing an error code and error message.
        */
        logError: function(errorObject) {

            // Console only exists in Firebug so check it exists before trying to write to it
            if (TVI.firebugCheck() === true) {

                // Check to see if there is an errors colleciton
                if (errorObject.errors) {

                    // Loop through
                    var errorsLength = errorObject.errors.length;
                    for (i = 0; i < errorsLength; i++) {
                        console.error('TVI Error: ' + errorObject.errors[i].code + ' - ' + errorObject.errors[i].message);
                    }
                }
                else {
                    console.error('TVI Error: ' + errorObject.code + ' - ' + errorObject.message);
                }

            }
        },

        /**
        * Log a warning to the Firebug error console.
        * @param {string} warning - The warning to be shown
        */
        logWarning: function(warning) {

            // Console only exists in Firebug so check it exists before trying to write to it
            if (TVI.firebugCheck() === true) {
                console.warn(warning);
            }
        },

        /**
        * Log a comment to the Firebug console.
        * @param {string} comment - The comment to show
        */
        logComment: function(comment) {

            // Console only exists in Firebug so check it exists before trying to write to it
            if (TVI.firebugCheck() === true) {
                console.info(comment);
            }
        },

        /**
        * Wraps up Firebug's console.dir function.
        * @param {Object} o - The object to bad added to the console
        */
        logDir: function(o) {

            // Console only exists in Firebug so check it exists before trying to write to it
            if (TVI.firebugCheck() === true) {
                console.dir(o);
            }
        },

        /**
        * Start a timer in Firebug's console.
        * @param {string} name - The name of the timer. Must match the logTimerEnd name.
        */
        logTimer: function(name) {

            // Console only exists in Firebug so check it exists before trying to write to it
            if (TVI.firebugCheck() === true) {
                console.time(name);
            }
        },

        /**
        * Stops a timer in Firebug's console.
        * @param {string} name - The name of the timer. Must match the start timer name.
        */
        logTimerEnd: function(name) {

            // Console only exists in Firebug so check it exists before trying to write to it
            if (TVI.firebugCheck() === true) {
                console.timeEnd(name);
            }
        },

        /**
        * Starts a group of nested comments/warnings/errors in Firebug's console.
        * @param {string} name - The name of the group. Must match the logGroupEnd name.
        */
        logGroup: function(name) {

            // Console only exists in Firebug so check it exists before trying to write to it
            if (TVI.firebugCheck() === true) {
                console.group(name);
            }
        },

        /**
        * Ends a group of nested comments/warnings/errors in Firebug's console.
        * @param {string} name - The name of the group. Must match the start name.
        */
        logGroupEnd: function(name) {

            // Console only exists in Firebug so check it exists before trying to write to it
            if (TVI.firebugCheck() === true) {
                console.groupEnd(name);
            }
        },

        /**
        * Starts Firebug's profiler.
        * @param {string} title - Optional title for the profiler report.
        */
        logProfile: function(title) {

            // Console only exists in Firebug so check it exists before trying to write to it
            if (TVI.firebugCheck() === true) {
                console.profile(title);
            }
        },

        /**
        * Stops Firebug's profiler.
        */
        logProfileEnd: function() {

            // Console only exists in Firebug so check it exists before trying to write to it
            if (TVI.firebugCheck() === true) {
                console.profileEnd();
            }
        },

        /**
        * Prints an interactive stack trace of JavaScript execution at the point where it is called.
        */
        logTrace: function() {

            // Console only exists in Firebug so check it exists before trying to write to it
            if (TVI.firebugCheck() === true) {
                console.trace();
            }
        }

    });

})();



///////////////////////////////////////////////////////


// declare web namespace
WEB = {};

// apply default properties and methods to the web namespace
TVI.apply(WEB, {

    /**
    * Remember whether the form is currently open or closed
    */
    isFormOpen: false,

    /**
    * Opens purple form dropdown at top of page
    * @param {String} openEaseType - easing method when opening form
    * @param {Number} openEaseDuration - duration of opening form
    */
    openForm: function(params) {

        var defaultParams = {
            easeType: 'jswing',
            easeDuration: 'fast',
            formName: 'getQuote'
        };

        var params = TVI.apply(defaultParams, params);

        //hide any tooltips
        //if (WEB.purpleToolTipManager) {
        //    WEB.purpleToolTipManager.hideAllTips();
        //}

        if (!WEB.isFormOpen) {

            WEB.isFormOpen = true;


            //Slide down unless IE6, in which case 'show'
            if ($('body').hasClass('browserIE6')) {
                $('.dropDown.' + params.formName).show();
            } else {
                //$('.dropDown.' + params.formName + ' .middle').slideDown(params.easeDuration, params.easeType);
	         $('.dropDown.' + params.formName).show();
 	         $('.dropDown.' + params.formName).animate({marginLeft: '0px'}, '1000', 'easeOutSine');


            }

            //$('.dropDown.' + params.formName + ' .top').show();
            //$('.dropDown.' + params.formName + ' .bottom').show();

        } else if (WEB.isFormOpen) {

            //Fade to new content unless IE6, in which case 'show'
            if ($('body').hasClass('browserIE6')) {
                $('.dropDown .dropDownContainer').hide(function() {

                    $('.dropDown').hide();
		      $('.dropDown').css({'margin-left': '-'+$('.dropDown').css('width')});
                    $('.dropDown.' + params.formName).show();
		      $('.dropDown.' + params.formName).css({'margin-left': '0'});
                    $('.dropDown .dropDownContainer').show();

/*
                    $('.dropDown .middle').hide();
                    $('.dropDown.' + params.formName + ' .middle').show();
                    $('.dropDown .top').hide();
                    $('.dropDown.' + params.formName + ' .top').show();
                    $('.dropDown .bottom').hide();
                    $('.dropDown.' + params.formName + ' .bottom').show();
                    $('.dropDown .dropDownContainer').show();
*/
                });
            } else {
                $('.dropDown .dropDownContainer').fadeTo('fast', 0, function() {

                    $('.dropDown').hide();
                    $('.dropDown').css({'margin-left': '-'+$('.dropDown').css('width')});
                    $('.dropDown.' + params.formName).show();
		      $('.dropDown.' + params.formName).css({'margin-left': '0'});
                    $('.dropDown .dropDownContainer').fadeTo('normal', 1);
/*
                    $('.dropDown .middle').hide();
                    $('.dropDown.' + params.formName + ' .middle').show();
                    $('.dropDown .top').hide();
                    $('.dropDown.' + params.formName + ' .top').show();
                    $('.dropDown .bottom').hide();
                    $('.dropDown.' + params.formName + ' .bottom').show();
                    $('.dropDown .dropDownContainer').fadeTo('normal', 1);
*/
                });
            }
        }

/*
        //reset form
        switch (params.formName) {
            case "getQuote":
                topnavQuoteReset();
                break;
            case "requestDemo":
                topnavDemoReset();
                break;
            case "contactUs":
                topnavContactReset();
                break;
        }
*/
        //google analytics
        switch (params.formName) {
            case "getQuote":
                //pageTracker._trackPageview('/formQuoteOpen');
                break;
            case "requestDemo":
                //pageTracker._trackPageview('/formDemoOpen');
                break;
            case "contactUs":
                //pageTracker._trackPageview('/formContactOpen');
                break;
        }

    },

    /**
    * Closes purple form dropdown at top of page
    * @param {String} closeEaseType - easing method when closing form
    * @param {Number} closeEaseDuration - duration of closing form
    */
    closeForm: function(params) {

        if (WEB.isFormOpen) {

            var defaultParams = {
                easeType: 'jswing',
                easeDuration: 'normal'
            };

            var params = TVI.apply(defaultParams, params);
/*
            //hide any tooltips
            if (WEB.purpleToolTipManager) {
                WEB.purpleToolTipManager.hideAllTips();
            }
*/
            //Slide up unless IE6, in which case 'hide'
            if ($('body').hasClass('browserIE6')) {
                $('.dropDown').hide();

/*
                $('.dropDown .top').hide();
                $('.dropDown .middle').hide();
                $('.dropDown .bottom').hide();
*/
            } else {

	     

    $('.dropDown').animate({

      marginLeft: '-'+$('.dropDown').css('width')

    }, '1000', 'easeInSine', function() {$('.dropDown').hide();});

	//$('.dropDown').hide();

/*
                $('.dropDown .top').hide();
                $('.dropDown .middle').slideUp(params.easeDuration, params.easeType);
                $('.dropDown .bottom').slideUp(params.easeDuration * 0.75, params.easeType);
*/
            }

            WEB.isFormOpen = false;


        }
    }
});



// Check that the page has loaded
$(document).ready(function() {

//alert("doc ready");

    //$('#forms').load('/dropDownForms.htm', function() {

        topnavInit();

        // DROP DOWN BOX FUNCTIONALITY    
        $('#side-tabs li').click(function() {

            if ($(this).hasClass('quote')) {
                WEB.openForm({
                    easeType: 'easeOutElastic',
                    easeDuration: 2000,
                    formName: 'getQuote'
                });
            } else if ($(this).hasClass('demo')) {
                WEB.openForm({
                    easeType: 'easeOutElastic',
                    easeDuration: 2000,
                    formName: 'requestDemo'
                });
            } else if ($(this).hasClass('contact')) {
                WEB.openForm({
                    easeType: 'easeOutElastic',
                    easeDuration: 2000,
                    formName: 'contactUs'
                });

                // Pre-load the picture of our office
                //$('.mapCol3').empty().append('<img src="/i/Office.jpg" alt="TVI offices" />');

            }

            $('#side-tabs li a').removeClass('selectedTab'); // Remove 'hover' from all menu items (reset)

            $(this).find('a').addClass('selectedTab'); // add 'hover' to menu item that was cliked

            return false;
        });


        // Add close functionality top drop down
        $('.dropDown .close').click(function() {

            WEB.closeForm({
                easeDuration: 400
            });

            $('#side-tabs li a').removeClass('selectedTab'); // Remove 'hover' from all menu items (reset)
        });



    //});



}); 



function topnavInit() {

    //setup quote form
    topnavSetupQuote();

    //setup demo form
    topnavSetupDemo();

    //setup contact form
    topnavSetupContact();

}

function topnavSetupQuote() {
// setup button actions if there are any
    //reset form
    //topnavQuoteReset();

    //setup tooltips
    //topnavQuoteToolTips();

    //add click event
    $('#btn_quote').click(function() {

        //topnavQuote();
	alert("quote button clicked");

    });

}

function topnavSetupDemo() {
// setup button actions if there are any
    //request a demo form
    //topnavDemoReset();

    //topnavDemoToolTips();

    $('#btn_requestDemo').click(function() {

	alert("demo button clicked");
        // topnavDemo();

    });

}

function topnavSetupContact() {

// setup button actions if there are any

    $('#btn_contact').click(function() {

        // topnavContact();
	alert("contact button clicked");

    });

}



