var splCharRegExp = /^[a-z0-9\_]+$/i;
var splChar = "!@#$%^&*()+=-[]\\\';,./{}|\":<>?";

var iCustomerNameCharsRegExp = /^[a-z0-9\_\-\.\s]+$/i;
var iCustomerNameChars = "!@#$%^&*+=[]\\\';,/{}|\":<>?";

var iCharsRegExp = /^[a-z\_]+$/i;
var iChars = "!@#$%^&*()+=-[]\\\';,./{}|\":<>?1234567890";

var invCharsRegExp = /^[a-z\_]+$/i;
var invChars = "!@#$%^&*()+=[]\\\';,./{}|\":<>?1234567890";

var iACharsRegExp = /^[a-z0-9\_\s]+$/i;
var iAChars = "!@#$%^&*()+=-[]\\\';,./{}|\":<>?";

var iSpecialCharsRegExp = /^[0-9\_]+$/i;
var iSpecialChars = "!@#$%^&*()+=-[]\\\';,./{}|\":<>?ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";

var postalCodeRegExp = /(^\d{5}$)|(^\d{5}-\d{4}$)/;
        
var DistribMain = new function() {
  var _flag = false;
  var _scroll;

  this.initialize = function() {
    if (!_flag) {
      _flag = true;
      initialize.call(this);
    }
  }

  function initialize() {
	_scroll = new DynamicScroll();
	assignWindowResizeHandler();
    configNavigation();
	assignAccountDetailsHandler();
    checkForViewOnly();
	if (!$('.tablesorter').length) this.updateDynamicScroll();
    assignMaskHandler();
	redrawContainer();
    handleMultipleValidationErrorDivs();
  }
  
  this.disableHeader = function(b) {
	  if (b == null) b = true;
	  function Bool() { return (b) ? false : true; }
	  function CName(e, c) { b ? $(e).addClass(c) : $(e).removeClass(c); }
	  
	  $('#branding .details a').each(function() {
			CName(this, 'disabled');
			this.onclick = function() { return Bool() }
			if (this.id == 'changeFleetAccountInHeader') CName(this, 'hide');
	  });
	  
	  CName($('#nav'), 'disabled');
	  $('#nav > li > a').each(function() {
	  		this.onclick = function() { return Bool() }
	  });
  }
  
  this.updateDynamicScroll = function() {
	  function update() {(_scroll.logic()) ? _scroll.show() : _scroll.hide();}
	  if (!_scroll.logic()) $(window).resize(update);
	  update();
	  redrawContainer();
  }
  
  function assignWindowResizeHandler() {
	  if (!$.browser.msie) return true;
	  var new_width = $(window).width() < 1100 ? 970 : "85%";
	  $('.container').css('width', new_width);
	  $(window).resize(assignWindowResizeHandler);
  }

  function configNavigation() {
	  var model = new NavigationModel();
	  var factory = new SubMenuFactory();
	  var views = $('#nav ul');
		  views.each(function() {
			  var controller = new SubMenuController();
				  controller.initialize(model);
			  var view = factory.order(this);
				  view.setupMenu(controller);
				  model.subscribe(view);
		  });
		  
	  $(window).resize(function() {
			$(model.getObservers()).each(function() { 
					this.positionSubMenuHorizontally();
			});
	  });
  }
  
  function assignAccountDetailsHandler() {
	  var inner = $('.additional_details_inner');
	  var outer = $('.additional_details_outer').css({
			width: inner.outerWidth(),
			height: inner.outerHeight()
	  });
	  $('#additional_details').hover(
			function() {
				outer.stop().css('opacity', 0).show().animate({opacity: .75});
				inner.stop().css('opacity', 0).show().animate({opacity: 1});
			},
			function() {
				outer.stop().animate({opacity:0}, {complete:function(){outer.hide()}});
				inner.stop().animate({opacity:0}, {complete:function(){inner.hide()}});
			}
  	);
  }

  function checkForViewOnly() {
    $(".jq_viewOnly, .jq_fleetViewOnly").attr("disabled", true);
  }
  
  function DynamicScroll() {
	  this.logic = function() {
		  var wrapper = $('.content_main').scrollLeft(1);
		  return (wrapper.scrollLeft()) ? true : false;
	  }

	  this.show = function() {
		  update();
		  $(window).bind('scrollstop resize', update);
	  }

	  this.hide = function() {
		  $(window).unbind('scrollstop resize', update);
		  $('#content_container, #footer, .content_main').removeAttr('style');
	  }

	  function update() {
		  var cont_main = $('.content_main');
		  var container = $('#content_container');
	  	  var max_height = $('.content_wrapper').outerHeight();
		  var win_pos = $(window).height() + $(window).scrollTop();
		  var div_height = win_pos - cont_main.offset().top;
		  var new_height = (div_height <= max_height) ? div_height : max_height;
		  var foot_opaque = (div_height <= max_height) ? 0 : 1;
			  cont_main.css('height', 'auto');
			  container.css('height', 'auto').css('height', container.outerHeight());
			  cont_main.css('height', new_height);
			  $('#footer').stop().animate({opacity: foot_opaque}, 'fast');
	  }
  }

  function assignMaskHandler() {
	$(document).mouseup(redrawContainer);
  }
  
  function redrawContainer() {
	  $('.mask_lower').css('visibility', 'hidden');
	  $('.mask_lower').css('visibility', 'visible');
  }
}

var $j = jQuery; //just in case
$(document).ready(function() {
  DistribMain.initialize();
});

/*
    Function to display a jquery alert box.
 */
var wexOpenAlert = function( options ) {
   var defaults = {
        ht: 200
        , wth: 400
        , title: 'Please Note:'
        , form: {}
        , msgs: {}
        , btnTxt1: 'OK'
        , btn1Callback: function() {
                        $(this).dialog("close");
                        if ( options && options.msgs && options.msgs.length > 1 ) {
                            options.msgs.shift();//remove the first element in the array
                            wexOpenAlert( options );
                        }
                      }
       , buttons: {}
    };
    if ( !options ) { options = {}; }
    var overrides = $.extend( {}, defaults, options );
    var alertBtn = {};
    alertBtn[overrides.btnTxt1] = overrides.btn1Callback;
    $('#dialog').dialog('option', 'buttons', alertBtn);
    $('#dialog').wexOpenDialog({
          height: overrides.ht
         , width: overrides.wth
         , title: overrides.title
         , buttons: alertBtn
      });
    $("#dialogContent").html(overrides.msgs[0]);
}

/*
    Function to display a jquery confirm box.
 */
var wexOpenConfirm = function( options ) {
    var defaults = {
        ht: 200
        , wth: 400
        , title: 'Confirm'
        , form: {}
        , msgs: {}
        , btnTxt1: 'Cancel'
        , btnTxt2: 'OK'
        , pleaseWaitEnabled: false
        , pleaseWaitText: 'Processing. Please wait.'
        , btn1Callback: function() {
                        $(this).dialog("close");
                      }
        , btn2Callback: function() {
                        $(this).dialog("close");
                        if ( options && options.msgs && options.msgs.length > 1 ) {
                            options.msgs.shift();//remove the first element in the array
                            wexOpenConfirm( options );
                        } else if (options && options.form ) {
                            //submit the form here...
                            if(options.pleaseWaitEnabled) {
                                 displayPleaseWaitMsg(options.pleaseWaitText);
                            }
                            options.form.submit();
                        }
                      }
        , buttons: {}
    };
    if ( !options ) { options = {}; }
    var overrides = $.extend( {}, defaults, options );
    var btn = {};
    btn[overrides.btnTxt1] = overrides.btn1Callback;
    btn[overrides.btnTxt2] = overrides.btn2Callback;
    $('#dialog').dialog('option', 'buttons', btn);
    $('#dialog').wexOpenDialog({
           height: overrides.ht
         , width: overrides.wth
         , title: overrides.title
         , buttons: btn
      });
    $("#dialogContent").html(overrides.msgs[0]);
};

/*Function to manipulate multiple error divs*/
  function handleMultipleValidationErrorDivs () {
      var i = 0;
      $("div[id='validation_alert']").each(function () {
            if(i > 0) {
                $(this).attr("id","validation_alert"+i);
            }
            i++;
      });
      i = 0;
      $("span[id='noOfErrorsMessageTxt']").each(function () {
            if(i > 0) {
                $(this).attr("id","noOfErrorsMessageTxt"+i);
            }
            i++;
      });
  }