if(!this.LoadoutApp)
{ 
  LoadoutApp = {
    viewControllers: {},
    currentFaction: '',
    armorData:  [
      {"name": "Light", "cost": 200 },
      {"name": "Medium", "cost": 600 },
      {"name": "Special", "cost": 800 },
      {"name": "Heavy", "cost": 1000}
    ],
    gearData:  [
      {"name": "None","cost": 0, "heavy": false},
      {"name": "First Aid Kit", "cost": 600, "heavy": false},
      {"name": "Fragmentation Grenade", "cost": 400, "heavy": false},
      {"name": "Smoke Grenade", "cost": 300, "heavy": false},
      {"name": "Repair Kit", "cost": 1000, "heavy": false},
      {"name": "Medical Kit", "cost": 1000, "heavy": false},
      {"name": "Acoustic Locator", "cost": 200, "heavy": false},
      {"name": "Anti-Personnel Mines", "cost": 800, "heavy": false},
      {"name": "Anti-Tank Mines", "cost": 600, "heavy": false},
      {"name": "Explosives Detector", "cost": 600, "heavy": false},
      {"name": "Motion Sensor", "cost": 800, "heavy": false},
      {"name": "Sensor Jammer", "cost": 400, "heavy": false},
      {"name": "Gas Grenade", "cost": 600, "heavy": false},
      {"name": "RPG", "cost": 400, "heavy": true},
      {"name": "Improved RPG", "cost": 1000, "heavy": true}
    ],
    mainWeaponData: [
      {"name": { RAVEN: "Hollis A3", VALOR: "M4A1", SVER: "AK-74U" }, "cost": 500, "attachments": "ar_group" },  
      {"name": { RAVEN: "ATAC 2000", VALOR: "SFCR-LW", SVER: "AG-94" }, "cost": 700, "attachments": "ar_group" },  
      {"name": { RAVEN: "R-553", VALOR: "SFCR-HW", SVER: "AK-103" }, "cost": 800, "attachments": "ar_group" },  
      {"name": { RAVEN: "F90", VALOR: "KP5", SVER: "Vipera-2" }, "cost": 400, "attachments": "smg_group"},
      {"name": { RAVEN: "Boudini 12 Gauge", VALOR: "12 Gauge Pump", SVER: "T-195" }, "cost": 600, "attachments": "shotty_group"},
      {"name": { RAVEN: "APEX 100", VALOR: "MK46 Mod0", SVER: "RTK-74" }, "cost": 600, "attachments": "mg_group"},
      {"name": { RAVEN: "KP45 MG", VALOR: "MK43 Mod1", SVER: "PKP MG" }, "cost": 800, "attachments": "mg_group"},
      {"name": { RAVEN: "H M 90", VALOR: "MK14 mod 0 EBR", SVER: "SASR" }, "cost": 600, "attachments": "sniper_group_1"},
      {"name": { RAVEN: "Janas SWS", VALOR: "L96AW", SVER: "S-98" }, "cost": 800, "attachments": "sniper_group_2"},
      {"name": { RAVEN: "AM50", VALOR: "Rollins LRRS", SVER: "AGVK" }, "cost": 1000, "attachments": "sniper_group_3"}
    ],
    attachments: {
      "ar_group": {
        "firepoint": [
          {"name": "No Attachment", "cost": 0 },
          {"name": "Suppressor","cost":200}
        ],
        "sight": [
          {"name": "No Attachment", "cost": 0 },
          {"name": "Reflex", "cost": 100},
          {"name": "Optical 4x", "cost": 200},
        ],
        "underbarrel": [
          {"name": "No Attachment", "cost": 0 },
          {"name": "Bipod", "cost": 200},
          {"name": "Foregrip", "cost": 200},
          {"name": "Grenade Launcher", "cost": 400}
        ]
      },
      "smg_group": {
        "firepoint": [
          {"name": "No Attachment", "cost": 0 },
          {"name": "Suppressor","cost":200}
        ],
        "sight": [
          {"name": "No Attachment", "cost": 0 },
          {"name": "Reflex", "cost": 100},
        ],
        "underbarrel": [
          {"name": "No Attachment Available", "cost": 0 },
        ]
      },
      "shotty_group": {
        "firepoint": [
          {"name": "No Attachment Available", "cost": 0 },
        ],
        "sight": [
          {"name": "No Attachment", "cost": 0 },
          {"name": "Reflex", "cost": 100},
        ],
        "underbarrel": [
          {"name": "No Attachment Available", "cost": 0 },
        ]
      },
      "mg_group": {
        "firepoint": [
          {"name": "No Attachment Available", "cost": 0 },
        ],
        "sight": [
          {"name": "No Attachment", "cost": 0 },
          {"name": "Reflex", "cost": 100},
        ],
        "underbarrel": [
          {"name": "No Attachment", "cost": 0 },
          {"name": "Bipod", "cost": 200},
          {"name": "Foregrip", "cost": 200},
        ]
      },
      "sniper_group_1": {
        "firepoint": [
          {"name": "No Attachment", "cost": 0 },
          {"name": "Suppressor","cost":200}
        ],
        "sight": [
          {"name": "Low Power", "cost": 300},
          {"name": "Optical 4x", "cost": 200},
        ],
        "underbarrel": [
          {"name": "No Attachment", "cost": 0 },
          {"name": "Bipod", "cost": 200},
          {"name": "Foregrip", "cost": 200},
        ]
      },
      "sniper_group_2": {
        "firepoint": [
          {"name": "No Attachment", "cost": 0 },
          {"name": "Suppressor","cost":200}
        ],
        "sight": [
          {"name": "Low Power", "cost": 300},
          {"name": "High Power", "cost": 400},
          {"name": "Variable Power", "cost": 500}
        ],
        "underbarrel": [
          {"name": "No Attachment", "cost": 0 },
          {"name": "Bipod", "cost": 200},
        ]
      },
      "sniper_group_3": {
        "firepoint": [
          {"name": "No Attachment Available", "cost": 0 },
        ],
        "sight": [
          {"name": "Low Power", "cost": 300},
          {"name": "High Power", "cost": 400},
          {"name": "Variable Power", "cost": 500}
        ],
        "underbarrel": [
          {"name": "Integrated Bipod", "cost": 0},
        ]
      },
      "secondary_group": {
        "firepoint": [
          {"name": "No Attachment", "cost": 0 },
          {"name": "Suppressor","cost":200}
        ]
      } 
    },
    secondaryWeaponData: [
      {"name": { RAVEN: "F57", VALOR: "M9", SVER: "IZ-443" }, "cost": 100, "attachments": "secondary_group"},
      {"name": { RAVEN: "KP7", VALOR: "Hollis MP", SVER: "Kurtis 45ACP" }, "cost": 300, "attachments": "secondary_group"}
    ],
    firepointData: [
      {"name": "No Attachment", "cost": 0 },
      {"name": "Suppressor","cost":200}
    ],
    sightData: [
      {"name": "No Attachment", "cost": 0 },
      {"name": "Reflex", "cost": 100},
      {"name": "Optical 4x", "cost": 200},
      {"name": "Low Power", "cost": 300},
      {"name": "High Power", "cost": 400},
      {"name": "Variable Power", "cost": 500}
    ],
    underbarrelData: [
      {"name": "No Attachment", "cost": 0 },
      {"name": "Bipod", "cost": 200},
      {"name": "Foregrip", "cost": 200},
      {"name": "Grenade Launcher", "cost": 400}
    ],

    init: function()
    {
      this.mainView =  jQuery('#wrapper_site');
      if( !jQuery.cookie('faction_name') )
      {
        this.viewControllers.factionViewController = new LoadoutApp.FactionViewController();
        this.viewControllers.factionViewController.showFactionPicker( jQuery('#wrapper_site') );
      }else
      {
        this.initWithFaction( jQuery.cookie('faction_name') );
      }
      jQuery('#tmpView').remove();
    },
    initWithFaction: function( factionName )
    {
      this.currentFaction = factionName;
      jQuery.cookie('faction_name', factionName , this.cookieOptions);
      this.totalViewControler = new LoadoutApp.TotalPointsViewController();
      this.mainView.append( this.totalViewControler.getView() );
      this.userModel = new LoadoutApp.UserModel( this.totalViewControler );


      var weapWrap = jQuery('<div id="wrapper_weapons"></div>');
      var bottomLeft = jQuery('<div id="bottomLeft"></div>');
      var bottomRight = jQuery('<div id="bottomRight"></div>');

      this.viewControllers.gear2View = new LoadoutApp.StuffViewController( new LoadoutApp.StuffModel( this.gearData ), "Gear 2", 'mainHeader' );
      bottomRight.append( this.viewControllers.gear2View.getView() );
      this.viewControllers.armorView = new LoadoutApp.StuffViewController( new LoadoutApp.StuffModel( this.armorData ), "Armor", 'mainHeader' );
      bottomRight.append( this.viewControllers.armorView.getView() );

      this.viewControllers.gear1View = new LoadoutApp.StuffViewController( new LoadoutApp.StuffModel( this.gearData ), "Gear 1", 'mainHeader' );
      bottomLeft.append( this.viewControllers.gear1View.getView() );
      this.viewControllers.heavyGearView = new LoadoutApp.StuffViewController( new LoadoutApp.StuffModel( this.gearData ), "Heavy Gear", 'mainHeader' );
      bottomLeft.append( this.viewControllers.heavyGearView.getView() );

      this.viewControllers.mainWeaponView = new LoadoutApp.WeaponViewController(new LoadoutApp.StuffModel( this.mainWeaponData ), "Primary Weapon", 'mainHeader', true );
      this.viewControllers.secondaryWeaponView = new LoadoutApp.WeaponViewController( new LoadoutApp.StuffModel( this.secondaryWeaponData ), "Secondary Weapon", 'mainHeader', false );
       
      weapWrap.append( this.viewControllers.mainWeaponView.getView() );
      weapWrap.append( this.viewControllers.secondaryWeaponView.getView() );
      this.mainView.append( weapWrap );
      this.mainView.append( bottomLeft );
      this.mainView.append( bottomRight );
      jQuery('#button_changeFaction').click( function()
      {
        LoadoutApp.changeFaction();
      });
    },
    pointsChange: function( delta )
    {
      this.userModel.changePoints( delta );
    },
    changeFaction : function()
    {
      // this.controllers.treeController.removeView();
      // this.controllers.detailView.removeView();
      // this.controllers.header.removeView();
      jQuery('#totalPointsWrapper, #wrapper_weapons, #bottomLeft, #bottomRight').remove(); 
      jQuery.cookie('faction_name', null, this.cookieOptions);
      this.init();
    }  

  }; 

}

(function(){

LoadoutApp.UserModel =  function( myView )
{
  var _maxPoints = 3400;
  var _currentPoints = 0;
  var _view = myView;
  return {
    changePoints: function( delta )
    {
      _currentPoints += delta;
      _view.updatePoints( _maxPoints, _currentPoints);
    }
  }
}

LoadoutApp.StuffModel = function( data )
{
  var _data = data;
  return {
    getMaxIndex : function()
    {
      return _data.length - 1;
    },
    getDataAt : function( index )
    {
      return ( index >= 0 && index < _data.length ) ? _data[ index ] : false;
    }
  };
}

LoadoutApp.StuffViewController = function( model, name, className )
{
  var _model = model;
  var _view = new LoadoutApp.StuffView( className );
  var _currentIndex = 0;
  var _currentPointTotal = 0;
  var _maxIndex = _model.getMaxIndex();
  if(_maxIndex == 0)
  {
    jQuery('.nextButton',_view).addClass('disabledArrow');
  }
  var _updateView = function( data )
  {
    var data = _model.getDataAt( _currentIndex ); 
    LoadoutApp.pointsChange( data.cost - _currentPointTotal );
    _currentPointTotal = data.cost;
    jQuery('.itemLabel', _view).text( data.name );
    jQuery('.itemCost', _view).text( data.cost );
  };
  jQuery('.titleBlock', _view).text( name );
  _updateView()
  jQuery('.prevButton', _view).click( function()
  {
    if(_currentIndex == _maxIndex )
    {
      jQuery( '.nextButton', _view ).removeClass('disabledArrow');
    }
    if(_currentIndex > 0 )
    {
      _currentIndex--;
      _updateView();
    }
    if(_currentIndex == 0 )
    {
      jQuery(this).addClass('disabledArrow');
    }
  });
  jQuery('.nextButton', _view).click( function()
  {
    if(_currentIndex == 0 )
    {
      jQuery( '.prevButton', _view ).removeClass('disabledArrow');
    }
    if(_currentIndex < _maxIndex )
    {
      _currentIndex++;
      _updateView();
    }
    if(_currentIndex == _maxIndex )
    {
      jQuery(this).addClass('disabledArrow');
    }

  });
  return {
    getView: function()
    {
      return _view;
    },
    currentValue: function()
    {
      return _currentPointTotal;
    }
  }
}

LoadoutApp.WeaponViewController = function( model, name, className, isPrimary )
{
  var _model = model;
  var _primary = isPrimary;
  var _myID = (_primary) ? ' id="wrapper_primaryWeapon"' : ' id="wrapper_secondaryWeapon"';
  var _view = jQuery('<div'+ _myID + '></div>');
  var _weaponView = new LoadoutApp.StuffView( className );
  _view.append( _weaponView );
  var _subviews = [];
  var _currentIndex = 0;
  var _currentPointTotal = 0;
  var _maxIndex = _model.getMaxIndex();
  var _updateView = function( data )
  {
    var data = _model.getDataAt( _currentIndex ); 
    LoadoutApp.pointsChange( data.cost - _currentPointTotal );
    _currentPointTotal = data.cost;
    jQuery('.itemLabel', _weaponView).text( data.name[ LoadoutApp.currentFaction ] );
    jQuery('.itemCost', _weaponView).text( data.cost );
    jQuery('.stuffWrapper:gt(0)',_view).remove();
    _updateSubview( 0, LoadoutApp.attachments[ data.attachments ].firepoint,  "Firepoint" );
    if( _primary )
    {
      _updateSubview( 1,LoadoutApp.attachments[ data.attachments ].sight,  "Sight" );
      _updateSubview( 2,LoadoutApp.attachments[ data.attachments ].underbarrel, "Underbarrel" );
    }
  };
  var _updateSubview = function( idx, model, name )
  {
    if( _subviews[ idx ] )
    {
      LoadoutApp.pointsChange( -1 *  _subviews[ idx ].currentValue() );
    }
    _subviews[ idx ] = new LoadoutApp.StuffViewController( new LoadoutApp.StuffModel( model ), name, 'subHeader' );
    _view.append( _subviews[ idx ].getView() );
  };
  jQuery('.titleBlock', _weaponView).text( name );
  _updateView()
  jQuery('.prevButton', _weaponView).click( function()
  {
    if(_currentIndex == _maxIndex )
    {
      jQuery( '.nextButton', _weaponView ).removeClass('disabledArrow');
    }
    if(_currentIndex > 0 )
    {
      _currentIndex--;
      _updateView();
    }
    if(_currentIndex == 0 )
    {
      jQuery(this).addClass('disabledArrow');
    }
  });
  jQuery('.nextButton', _weaponView).click( function()
  {
    if(_currentIndex == 0 )
    {
      jQuery( '.prevButton', _weaponView ).removeClass('disabledArrow');
    }
    if(_currentIndex < _maxIndex )
    {
      _currentIndex++;
      _updateView();
    }
    if(_currentIndex == _maxIndex )
    {
      jQuery(this).addClass('disabledArrow');
    }

  });
  return {
    getView: function()
    {
      return _view;
    }
  }
}

LoadoutApp.StuffView = function( className )
{
  var _html = '<div class="stuffWrapper"><p class="titleBlock ' + className + '">Default Title</p>';
  _html += '<p class="prevButton disabledArrow"><img src="/img/loadoutApp/loadoutPrevButton.gif" alt="&lt;" /></p>';
  _html += '<p class="nextButton"><img src="/img/loadoutApp/loadoutNextButton.gif" alt="&gt;" /></p>';
  _html += '<p class="itemLabel">Default Item Name</p><p class="itemCost">000</p></div>';
  return jQuery( _html );
}

LoadoutApp.TotalPointsViewController = function()
{
  var _view = new LoadoutApp.TotalPointsView();
  return {
    getView: function()
    {
      return _view;
    },
    updatePoints: function( max, used )
    {
     jQuery('#totalPointsLabel').text( max );
     jQuery('#usedPointsLabel').text( used );
     jQuery('#availablePointsLabel').text(  (max - used) );
     if( (max - used) < 0 )
     {
       jQuery('#availablePointsLabel').addClass('negativePoints');
     }else
     {
       jQuery('#availablePointsLabel').removeClass('negativePoints');
     }
    }
  }
}

LoadoutApp.TotalPointsView = function()
{
  var _html = jQuery('<div id="totalPointsWrapper"></div>'); 
  _html.append('<p id="button_changeFaction"><img src="/img/skillTree/backgrounds/button_changeFaction.png" alt="change faction" /></p>');
  _html.append('<p id="pointsAvailableWrapper">AVAILABLE: <span id="availablePointsLabel">0</span></p>');
  _html.append('<p id="totalPointsUsedWrapper">USED: <span id="usedPointsLabel">0</span> / <span id="totalPointsLabel">0</span></p>');
  return _html;
}

/*
TODO: Get this working for now, but abstract out (along with error dialog) as it's own file / standalone.
*/
  LoadoutApp.FactionViewController = function()
  {
    var _view = false;
    return {
      showFactionPicker : function( view )
      {
        if(!_view) { _view = new LoadoutApp.FactionView( this ); }
         view.append( _view ); 
      },
      handleFactionButtonClick : function( factionName )
      {
        this.hideFactionPicker();
        LoadoutApp.initWithFaction( factionName );
      },
      hideFactionPicker : function()
      {
        _view.remove();
      }
    }
  }

  LoadoutApp.FactionView = function( controller )
  {
    var _controller = controller;
    var _html = '<div id="factionPickerView"><h3>Choose your Faction</h3></div>'; // load from file?
    var _sverButton = new LoadoutApp.Button( 'SVER', 'sverFactionButton', function(){ _controller.handleFactionButtonClick('SVER')}, 'button_faction' ); 
    var _ravenButton = new LoadoutApp.Button( 'Raven',  'ravenFactionButton', function(){ _controller.handleFactionButtonClick('RAVEN')}, 'button_faction'); 
    var _valorButton = new LoadoutApp.Button( 'VALOR', 'valorFactionButton',  function(){ _controller.handleFactionButtonClick('VALOR')}, 'button_faction' ); 

    return jQuery( _html ).append( _sverButton, _ravenButton, _valorButton );
  }

  LoadoutApp.Button = function( label, id, handler, classes)
  {
    var _html = '<div class="button"></div>';
    var _button = jQuery( _html );
    _button.text( label );
    if( handler ){ _button.click( handler ); }
    if( id ){ _button.attr( 'id', id ); }
    if( classes ){ _button.addClass( classes ); }
    return _button;
  }
})();

jQuery( document ).ready( function()
{
  LoadoutApp.init();
});

