if(!String.prototype.pad) {
    String.prototype.pad = function(n, c, t) {

        var s=this;

        if(s.length < n) {
            if(typeof t == 'undefined' || t.length == 0) {
                t = 'left';
            }
            while(s.length<n) {
                s =(t=='left') ? c+s : s+c;
            }
        }

        return s.toString();

    };
}
/**
 * dbPopWin: db Popup Windows Plugin for JQuery - 04 Jul 08
 * http://hypertextjunkie.com/assets/js/jquery/dbpopwin/
 * ex: return $.dbPopWin($(this).attr('href'), { dbPopWinWidth: 800, dbPopWinHeight: 600 });
 */
jQuery.dbPopWin = function(url, options) {

    options = jQuery.extend({
        /* default options */
        dbPopWinWidth:      800,
        dbPopWinHeight:     600,
        dbPopWinTarget:     'dbPopWin',
        dbPopWinScrollbars: 'yes',
        dbPopWinResizable:  'no',
        dbPopWinMenuBar:    'no',
        dbPopWinAddressBar: 'yes'
    }, options);

    /* center the window by default. */
    if(!options.dbPopWinY) {
        options.dbPopWinY = screen.height / 2 - options.dbPopWinHeight / 2;
    }

    if(!options.dbPopWinX) {
        options.dbPopWinX = screen.width / 2 - options.dbPopWinWidth / 2;
    }

    open(
        url,
        options['dbPopWinTarget'],
        'width= '      + options.dbPopWinWidth +
        ',height='     + options.dbPopWinHeight +
        ',top='        + options.dbPopWinY +
        ',left='       + options.dbPopWinX +
        ',scrollbars=' + options.dbPopWinScrollbars +
        ',resizable='  + options.dbPopWinResizable +
        ',menubar='    + options.dbPopWinMenuBar +
        ',location='   + options.dbPopWinAddressBar
       );

    return false;

};

/**
 * addNavEvents
 * @used: by ALL pages with primary nav
 * primary nav mouseovers
 */
function addNavEvents() {
	
    jQuery("#ul-nav li").each(function() {

        if(jQuery(this).hasClass('li-off')) {
            jQuery(this).hover(function() {

                jQuery(this).addClass('li-over');

            }, function() {

                jQuery(this).removeClass('li-over');

            });
        }

    });
	
}

/**
 * addFormButtonEvents
 * @used: by all Forms
 * adds special form button rollovers
 */
function addFormButtonEvents(){
	
    jQuery.each(['submit', 'cancel', 'upload', 'edit', 'preview', 'send', 'continueL'], function(bType) {

        jQuery("input." + bType + '-button').each(function() {

            jQuery(this).hover(function() {

                jQuery(this).addClass(bType + '-on');

            }, function() {

                jQuery(this).removeClass(bType + '-on');

            });

        });

    });

}

/**
 * ApplyActions
 * @used: by View/Comment Blog Pages
 */
function applyBlogActions() {
	
    jQuery(".blog-action").each(function() {

        jQuery(this).css({
            backgroundColor:    "#ACF775"
        }).animate({
            backgroundColor:    "#ffffff"
        }, 2000);

    });
	
    jQuery(".comment-action").each(function() {

        jQuery(this).css({
            backgroundColor:    "#ACF775"
        }).animate({
            backgroundColor:    "#ececec"
        }, 2000);

    });
	
    jQuery(".message-action").each(function() {

        jQuery(this).css({
            backgroundColor:    "#87d032"
        }).animate({
            backgroundColor:    "#ffffff"
        }, 4000);

    });
	
}

/**
 * formHighlights
 * activates the highlighting of elements within the form
 * ie: fieldset
 * used in SAP
 *
 */
function formHighlights() {
	
    jQuery(":input").each(function() {

        jQuery(this).focus(function() {

            jQuery(this).parent().addClass('focused');
            jQuery(this).parent().parent().addClass('focused');

        });
			
        jQuery(this).blur(function() {

            jQuery(this).parent().removeClass('focused');
            jQuery(this).parent().parent().removeClass('focused');

        });

    }); // end each

}

/**
 * setupDateFields
 * will make it so if a date field is set blank, ALL will be set blank
 * and if a date field is set(not blank), but others are blank, ALL will select first value(apart from selected)
 */
function setupDateFields() {

    jQuery('div.input.datetime select,div.input.date select, div.input.time select').change(function() {

        if(jQuery(this).val() == '') {
            jQuery(this).siblings('select').val('');
        } else {
            jQuery(this).siblings('select').each(function() {

                if(jQuery(this).val() == '') {
                    if(jQuery(this).attr('id').indexOf('year') != -1) {
                        jQuery(this).val((new Date()).getFullYear());
                    } else {
                        this.selectedIndex = 1;
                    }
                }

            });
        }

    });

}

/**
 * setupLoginJsParams
 * Saves 'js_check', 'js_screen', 'js_flash' Javascript params for use in the app
 */
function setupLoginJsParams() {

    jQuery('#login_form input').keypress(function(e) {

        if(e.keyCode == 13) {
            jQuery('#js_check').val(1);
            jQuery('#js_screen').val(screen.width + 'x'+ screen.height);
            UFO.getFlashVersion();
            jQuery('#js_flash').val(UFO.fv[0] + '.' + UFO.fv[1]);
            jQuery('#login_form').submit();
        }

    });

}

function jsTabs(show, hide, add, remove) {

    // add 'on' class
    jQuery(add).addClass("on");
    // show selected tab
    jQuery(show).show();
    // loop through and remove 'on' class
    jQuery(remove).removeClass("on");
    // loop through and hide other tabs
    jQuery(hide).hide();

}

function autoFillCallingCode(country) {
	
    // The default country value is what's render on the page initially
    var country_value = jQuery('#UserDetailCountry').attr('value');
	
    // if the country is being passed in(through a change using the country select)
    if(country) {
        country_value = country;
    }
	
    // Retrieve country codes via AJAX
    jQuery.getJSON("/user_details/get_calling_codes", function(json) {

        jQuery("input.calling_code").each(function() {

            // retreive sibling phone number input
            var sibling_id = jQuery(this).attr('id').substr(0,jQuery(this).attr('id').length-11);
			
            // if it's empty auto fill the country code
            if(jQuery('#'+sibling_id).attr('value') == '') {
                jQuery(this).attr('value', "+"+json[country_value]);
            }

        });

    });
	
}

/**
 * Fix Old Buttons For ID
 * we have "old buttons", which are slated to be restyled
 * but in the meantime this helps them work in ie7 & below
 */
function fixOldButtonsForIE() {

    jQuery('button.old-button').each(function() {

        var new_width = jQuery(this).width();
		
        if(new_width == 0){
            new_width = 80;
        }
		
        new_width += 12;
		
        jQuery(this).css({
            'overflow':'hidden',
            'width': new_width + 'px'
        });

    });

}

function langSwitchModal() {
	
    jQuery("a.footer_lang_link").each(function() {
		
        jQuery(this).click(function() {
			
            // snag some variables to be used below
            link = jQuery(this).attr('href');
            lang_id = jQuery(this).attr('id').split('_');
			
            // set the new language in the modal box content
            jQuery("#footer-lang-dialog-country").html(jQuery(this).html());
			
            jQuery("#footer-lang-dialog").dialog({
                bgiframe:   false,
                resizable:  false,
                modal:      true,
                close:      function(event) {

                    if(event.originalEvent) {
                        window.location = link;
                    }

                },
                overlay: {
                    backgroundColor:    '#000',
                    opacity:            0.5
                },
                buttons: {
                    'Yes, please save and proceed': function() {

                        // update the button to show the user we're working on saving it
                        jQuery(this).dialog('option', 'buttons', {
                            "Saving...": function(){}
                        });

                        // save user locale_id
                        jQuery.get('/user_details/update_locale_id/'+lang_id[1], function() {

                            // on complete close dialog and redirect to the link
                            jQuery(this).dialog('close');
                            window.location = link;

                        });

                    },
                    'No thanks': function() {

                        // close dialog and redirect to link
                        jQuery(this).dialog('close');
                        window.location = link;

                    }
                }
            });
			
            return false;
			
        });
		
    });
	
}

function langFormModal() {
	
    jQuery("#form-lang-dialog").dialog({
        autoOpen:   false,
        bgiframe:   false,
        resizable:  false,
        modal:      true,
        overlay:    {
            backgroundColor:    '#000',
            opacity:            0.5
        },
        buttons: {
            'Yes, save as my default language': function() {

                jQuery(this).dialog('close');

            },
            'No thanks': function() {

                // if they don't want to update their language revert back to previous value
                jQuery("select.lang_switch").val(jQuery('input#current_default_locale_id').attr('value'));
                jQuery(this).dialog('close');

            }
        }
    });
	
    // switch back to original language if they click the 'x' close button
    jQuery('#form-lang-dialog').bind('dialogclose', function(event) {

        if(event.originalEvent) {
            jQuery("select.lang_switch").val(jQuery('input#current_default_locale_id').attr('value'));
        }

    });
	
    jQuery("select.lang_switch").change(function() {

        if(jQuery('input#current_default_locale_id').attr('value') != jQuery('select.lang_switch').val()) {
            jQuery('#form-lang-dialog').dialog('open');
        }

    });

}

(function($){

    $.fn.highlight = function(cfg, ms){

        $(this).effect("highlight", cfg || {}, ms || 2000);

    };

})(jQuery);

// Startup for all pages
jQuery(document).ready(function() {
	
    addNavEvents();
    addFormButtonEvents();

    // pop links
    jQuery("a[rel=popup]").click(function() {

        jQuery.dbPopWin(this);

        return false;

    });

    setupDateFields();
    setupLoginJsParams();
    langSwitchModal();

    if(jQuery("#form-lang-dialog").length > 0) {
        langFormModal();
    }
	
});// end ready