/**
//\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
//\\\       \\\\\\\\|
//\\\ @@    @@\\\\\\| Hot Toddy Product
//\\ @@@@  @@@@\\\\\|
//\\\@@@@| @@@@\\\\\|
//\\\ @@ |\\@@\\\\\\| http://www.hframework.com
//\\\\  ||   \\\\\\\| (c) Copyright 2009 Richard York, All rights Reserved
//\\\\  \\_   \\\\\\|
//\\\\\        \\\\\| Use and redistribution are subject to the terms of the license.
//\\\\\  ----  \@@@@| http://www.hframework.com/license
//@@@@@\       \@@@@|
//@@@@@@\     \@@@@@|
//\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
*/

$$.extend({

  ToggleAddRemove : function($type)
  {
    return this.attr('src', $$.Path('/images/themes/aqua/icons/misc/' + $type.toLowerCase() + (arguments[2]? '_pressed' : '') + '.png'));
  },

  Product : {
    SelectedFile : null,

    EditCounter : 0,
    PriceCounter : 0,
    ImportCounter : 1,

    Ready : function()
    {
      this.EditCounter = Math.floor(Math.random() * 11);

      $$.Spotlight.SetListener('/plugins/hProduct/query');
      $$.Spotlight.SetSortColumn('`hProducts`.`hProductName`', 'ASC');

      $$.Spotlight.SetHandler(
        function(html) {
          $('div#hProductResults').html(html);
          this.AddProductEvents();
        }, this
      );

      $('input#hProductEditFile').click(
        function($e) {
          $e.preventDefault();
          var $node = $$.GetSelected('hProductFile');

          if ($node.length) {
            window.open(
              $$.Path(
                '/Applications/Editor', {
                  path: $(this).find('a').attr('title')
                }
              ),
              'Edit' + $$.Product.EditCounter,
              'width=1200,height=800,scrollbars=no,resizable=yes'
            );

            $$.Product.EditCounter++;
          } else {
            alert('No product is selected.');
          }
        }
      );

      $('input#hProductRemove').click(
        function($e) {
          $e.preventDefault();

          var $node = $$.GetSelected('hProductFile');

          $$.Unselect('hProductFile');
          $node.remove();
        }
      );

      $('input#hProductAdd').click(
        function($e) {
          $e.preventDefault();
          $$.Product.OpenChooser('AddProduct');
        }
      );

      $('input#hProductSave').click(
        function($e) {
          $e.preventDefault();
          this.disabled = true;
          $$.Product.Save();
        }
      );

      $('input#hProductNew').click(
        function($e) {
          $('input#hProductID').val(0);
          $('input#hProductPartNumber').val('');
          $('input#hProductMatch-0').attr('checked', 'checked');
          $('input#hProductName').val('');
      	  $('textarea#hProductDescription').val('');
          $('ul#hProductFiles').html('');
          $('input#hProductPricing').attr('disabled', 'disabled');

          $e.preventDefault();
        }
      );

      $('img#hProductPriceAdd, img#hProductPriceRemove, img#hProductImportAdd, img#hProductImportRemove')
        .mousedown(
          function() {
            $(this).ToggleAddRemove(this.id.indexOf('Add') != -1? 'Add' : 'Remove', true);
          }
        )
        .mouseup(
          function() {
            $(this).ToggleAddRemove(this.id.indexOf('Add') != -1? 'Add' : 'Remove');
          }
        )
        .click(
          function() {
            if (this.id.indexOf('Add') != -1) {
              if (this.id.indexOf('Price') != -1) {
                $$.Product.AddPrice($$.Product.PriceCounter);
                $$.Product.PriceCounter--;
              } else if (this.id.indexOf('Import') != -1) {
                $$.Product.AddImportField();
              }
            } else {
              // Remove
              if (this.id.indexOf('Price') != -1) {
                var $hProductPrice = $$.GetSelected('hProductPrice');

                if ($hProductPrice.length) {
                  $hProductPrice.remove();
                } else {
                  alert('No price is selected.');
                }
              } else if (this.id.indexOf('Import') != -1) {
                $$.Product.RemoveImportField();
              }
            }
          }
        );

      $('input#hProductPricing').click(
        function($e) {
          $e.preventDefault();
          $('form#hProductPriceDialogue').ToggleDialogue();
          $$.Product.GetPricing();
        }
      );

      $('form#hProductPriceDialogue img.hDialogueClose, input#hProductPriceDialogueClose').click(
        function($e) {
          $e.preventDefault();
          $$.Product.ClosePricingDialogue();
        }
      );

      $('input#hProductPriceDialogueSave').click(
        function($e) {
          $e.preventDefault();
          $$.Product.SavePricing();
        }
      );
  
      $('li#hApplicationMenu-Import').click(
        function() {
          $('form#hProductImportDialogue').ToggleDialogue();
        }
      );

      $('input.hProductImportAttachBaseProduct').click(
        function($e) {
          $e.preventDefault();
          $$.Product.OpenChooser('AddBaseProduct');
        }
      );

      $('form#hProductImportUpload img.hDialogueClose, input#hProductImportDialogueClose').click(
        function($e) {
          $e.preventDefault();
          $$.Product.CloseImportDialogue();
        }
      );
    },
  
    PricingEvents : function()
    {
      $('div.hProductPrice').each(
        function() {
          if (!this.hasPriceEvents) {
            this.hasPriceEvents = true;
            $(this).click(
              function() {
                $(this).Select('hProductPrice');
              }
            );
          }
        }
      );
    },

    AddImportField : function()
    {
      var $import = $('div.hProductImportTemplate').clone();
      $import.attr('class', 'hProductImportRow');
      $import.attr('id', 'hProductImportRow-' + this.ImportCounter);
  
      $('div#hProductImportFields').append($import);
  
      var $row = $('div#hProductImportRow-' + this.ImportCounter);
  
      this.SetImportCounter($row, this.ImportCounter);
      this.ImportCounter++;
      this.ImportEvents();
    },

    SetImportCounter : function($row, $id)
    {
      $row.attr('id', 'hProductImportRow-' + $id);
      $row.find('select.hProductImportType').attr('name', 'hProductImportType[' + $id + ']');
      $row.find('div.hProductImportColumnCell div').text($id);
  
      var $file = $row.find('input.hProductImportFile');
      
      if ($file.length) {
        $file.attr('name', 'hProductImportFile[' + $id + ']');
      }
    },
    
    RemoveImportField : function()
    {
      // Delete the selected row
      $$.GetSelected('hProductImportRow').remove();

      // Fix the counts... 
      this.ImportCounter = 1;
  
      $('div.hProductImportRow').each(
        function() {
          if (!$(this).hasClass('hProductImportTemplate')) {
            $$.Product.SetImportCounter(this, $$.Product.ImportCounter);
            $$.Product.ImportCounter++;
          }
        }
      );
    },
  
    ImportEvents : function()
    {
      $('div.hProductImportRow').each(
        function() {
          if (!$(this).hasClass('hProductImportTemplate') && !$(this).hasClass('hProductImportRowEvents')) {
            $(this)
              .addClass('hProductImportRowEvents')
              .click(
                function() {
                  $(this).Select('hProductImportRow');
                }
              );

            $(this).find('select.hProductImportType').click(
              function() {
                var $row = $(this).parents('.hProductImportRow');

                if ($(this).val() == 'hProductFile') {
                  $row.find('div.hProductImportAttachProductCell').addClass('hProductImportAttachProductCellOn');
                } else {
                  $row.find('div.hProductImportAttachProductCell').removeClass('hProductImportAttachProductCellOn');
                  $row.find('div.hProductImportAttachedProduct').html('');
                }
              }
            );
  
            $(this).find('input.hProductImportAttachProduct').click(
              function($e) {
                $e.preventDefault();
                $$.Product.OpenChooser('AddImportProduct');
              }
            );
          }
        }
      );
    },

    AddImportProduct : function($hFileID)
    {
      this.hProductImportFileID = $hFileID;
  
      $.get(
        $$.Path('/plugins/hFile/getFileInformation'), {
          hFileID: $hFileID,
          hFileUnique: 'ProductImport'
        },
        function(html) {
          var $row = $$.GetSelected('hProductImportRow');
          $row.find('div.hProductImportAttachedProduct').html( 
            html + 
            "<input type='hidden'" + 
                  " name='hProductImportFile[" + $row.SplitID() + "]'" + 
                  " class='hProductImportFile'" + 
                  " value='" + $$.Product.hProductImportFileID + "' />"
          );
        }
      );
    },

    ProcessImport : function($response)
    {
      this.CloseImportDialogue();
    },

    CloseImportDialogue : function()
    {
      $('form#hProductImportDialogue').ToggleDialogue();

      $('form#hProductImportDialogue').get(0).reset();

      $('div.hProductImportRow').each(
        function() {
          if (!$(this).hasClass('hProductImportTemplate')) {
            $(this).remove();
          }
        }
      );

      $('div.hProductImportAttachedBaseProduct').html('');
    },

    OpenChooser : function($callback)
    {
      this.hProductChoose = window.open(
        $$.Path(
          '/Applications/Finder/index.html', {
            dialogue: 'Choose',
            onChooseFile: '$$.Product.' + $callback
          }
        ),
        'hEditorChoose',
        'width=600,height=400,scrollbars=no,resizable=yes'
      );
      this.hProductChoose.moveTo((window.screen.width  - 600) / 2, (window.screen.height - 400) / 2);
      this.hProductChoose.focus();
    },
  
    AddBaseProduct : function($hFileID)
    {
      this.hProductImportBaseFileID = $hFileID;
  
      $('div.hProductImportAttachedBaseProduct')
        .load(
          $$.Path('/plugins/hFile/getFileInformation'), {
            hFileID: $hFileID,
            hFileUnique: 'ProductImportBase'
          }
        )
        .append(
          "<input type='hidden'" + 
                " class='hProductImportBase'" + 
                " name='hProductImportBase'" + 
                " value='" + this.hProductImportBaseFileID + "' />"
        );
    },

    AddProduct : function($hFileID)
    {
      $.get(
        $$.Path('/plugins/hFile/getFileInformation'), {
            hFileID: $hFileID,
            hFileUnique: 'Product'
        },
        function(html) {
          var $li = document.createElement('li');
          $li.className = 'hProductFile';
          $li.innerHTML = html;

          $('ul#hProductFiles').append($li);

          $$.Product.AddProductFileEvents();
          //$$.Product.ListEvents();
        }
      );
    },

    ClosePricingDialogue : function()
    {
      $('div.hProductPrice').each(
        function() {
          if (this.id) {
            $(this).remove();
          }
        }
      );

      $('input#hProductPriceBy-1').attr('checked', 'checked');

      this.PriceCounter = 0;

      $('form#hProductPriceDialogue').ToggleDialogue();
    },

    GetPricing : function()
    {
      // Pricing by part number takes precedence over pricing by products in a part number
      // To get pricing, there needs to be a selected product.
      var $hProduct     = $$.GetSelected('hProduct');
      var $hProductFile = $$.GetSelected('hProductFile');

      if ($hProduct.length && $hProductFile.length) {
        $.get(
          $$.Path(
            '/plugins/hProduct/getPricing', {
              hProductID: $hProduct.SplitID(),
              hFileID: $hProductFile.find('span.hFileProductID').text()
            }
          ),
          function(xml) {
            //$debug(hHTTP.responseText);
            this.AddPricing(xml);
          }
        );
      } else {
        alert('Unable to get pricing, no product file is selected.');
        this.ClosePricingDialogue();
      }    
    },

    SavePricing : function()
    {
      var $hProduct     = $$.GetSelected('hProduct');
      var $hProductFile = $$.GetSelected('hProductFile');

      if ($hProduct.length && $hProductFile.length) {
        var $post = 'hProductPriceBy=' + ($('input#hProductPriceBy-1').get(0).checked? 1 : 0);

        $('div.hProductPrice').each(
          function() {
            if (this.id) {
              $post += 
                  '&hProductPrice['           + $(this).SplitNumericID() + ']=' + $(this).find('input').val() +
                  '&hProductPriceCategoryID[' + $(this).SplitNumericID() + ']=' + $(this).find('select').val();
            }
          }, this
        );

        $.post(
          $$.Path(
            '/plugins/hProduct/savePricing', { 
              hProductID: $hProduct.SplitID(),
              hFileID: $hProductFile.find('span.hFileProductID').text()
            }
          ),
          $post,
          function() {
            // $debug(hHTTP.responseText);
            $$.Product.ClosePricingDialogue();
          }
        );
      } else {
        alert('Unable to save pricing, no product file is selected.');
      }
    },

    AddPrice : function($id)
    {
      var $hProductPrice = $('div.hProductPriceTemplate').clone();
      $hProductPrice.attr('class', 'hProductPrice');
      $hProductPrice.attr('id', 'hProductPrice-' + $id);
  
      $('div#hProductPriceWrapper').append($hProductPrice);

      if (arguments[1]) {
        var $select = $('div#hProductPrice-' + $id + ' select').get(0);

        for (var $i = 0; $i < $select.options.length; $i++) {
          if ($select.options[$i].value == arguments[1]) {
            $select.options[$i].selected = true;
          }
        }
      }

      if (arguments[2]) {
        $('div#hProductPrice-' + $id + ' input').val(arguments[2]);
      }

      this.PricingEvents();
    },

    AddPricing : function(xml)
    {
      var $hProductPriceBy = $(xml).find('hProductPriceBy').text();

      $('input#hProductPriceBy-' + ($hProductPriceBy == '1'? '1' : '0')).attr('checked', 'checked');

      $(xml).find('hProductPrice').each(
        function () {
          $$.Product.AddPrice(
            $(this).attr('hProductPriceID'),
            $(this).attr('hProductPriceCategoryID'),
            $(this).text()? $(this).text() : 0.00
          );
        }
      );
    },

    AddProductEvents : function()
    {
      $('div.hProductRecord').click(
        function() {
          $(this).Select('hProduct', $$.Product.GetSummary, $$.Product);
        }
      );
    },

    GetSummary : function()
    {
      $.get(
        $$.Path(
          '/plugins/hProduct/getProductData', {
            hProductID: $$.GetSelected('hProduct').SplitID()
          }
        ),
        function() {
          $$.Unselect('hProductFile');
          //$debug(hHTTP.responseText);
          this.GetProductData(xml);
  
          $('input#hProductPricing').removeAttr('disabled');
        }
      );
    },

    GetProductData : function(xml)
    {
      var $hProductID          = $(xml).find('hProductID').text();
      var $hProductPartNumber  = $(xml).find('hProductPartNumber').text();
      var $hProductName        = $(xml).find('hProductName').text();
      var $hProductDescription = $(xml).find('hProductDescription').text();
      var $hProductMatch       = parseInt($(xml).find('hProductMatch').text());

      $('input#hProductID').val($hProductID);
      $('input#hProductPartNumber').val($hProductPartNumber);
      $('input#hProductName').val($hProductName);
      $('textarea#hProductDescription').val($hProductDescription);

      $('input#hProductMatch-' + $hProductMatch).attr('checked', 'checked');

      var $ul = $('ul#hProductFiles');
      $ul.html('');

      $(xml).find('hFile').each(
        function() {
          var $hFileID    = $(this).find('hFileID').text();
          var $hFileIcon  = $(this).find('hFileIcon').text();
          var $hFileTitle = $(this).find('hFileTitle').text();
          var $hFilePath  = $(this).find('hFilePath').text();

          var $li = document.createElement('li');
          $li.className = 'hProductFile';

          var $span = document.createElement('span');
          $span.className = 'hFileProductID';
          $span.appendChild(document.createTextNode($hFileID));

          $li.appendChild($span);

          var $img = document.createElement('img');
          $img.className = 'hFileProductIcon';
          $img.alt = 'Product File Icon';
          $img.src = $hFileIcon;

          $li.appendChild($img);

          var $span = document.createElement('span');
          $span.className = 'hFileProductTitle';
          $span.appendChild(document.createTextNode($hFileTitle));

          $li.appendChild($span);

          var $span = document.createElement('span');
          $span.className = 'hFileProductPath';

          var $a = document.createElement('a');
          $a.href   = $hFilePath;
          $a.title  = $hFilePath;
          $a.target = '_blank';
          $a.appendChild(document.createTextNode($hFilePath));

          $span.appendChild($a);
          $li.appendChild($span);

          $ul.append($li);
        }
      );
  
      this.AddProductFileEvents();
    },
  
    AddProductFileEvents : function()
    {
      $('ul#hProductFiles li').each(
        function() {
          if (!this.hasProductEvent) {
            this.hasProductEvent = true;
            $(this).click(
              function() {
                $(this).Select('hProductFile');
              }
            );
          }
        }
      );
    },

    Save : function()
    {
      var $hFiles = [];
      var $i = 0;

      $('ul#hProductFiles span.hFileProductID').each(
        function() {
          $hFiles[$i] = parseInt($(this).text());
          $i++;
        }
      );

      $hFiles.sort();
  
      var $post =
        'hProductID='           + $('input#hProductID').val() +
        '&hProductPartNumber='  + encodeURIComponent($('input#hProductPartNumber').val()) +
        '&hProductMatch='       + ($('input#hProductMatch-1').get(0).checked? 1 : 0) +
        '&hProductName='        + encodeURIComponent($('input#hProductName').val()) +
        '&hProductDescription=' + encodeURIComponent($('textarea#hProductDescription').val()) +
        '&hProductFiles='       + ($hFiles.join(','));

      $$.Status.Message('Saving Product...');
  
      $.post(
        $$/Path('/plugins/hProduct/save'),
        $post,
        function(xml) {
          // $debug(hHTTP.responseText);
          $('input#hProductID').val($(xml).find('response').text());
          
          $$.Status.Message('Product Saved!', 'Fade');

          $('input#hProductSave').removeAttr('disabled');
          $('input#hProductPricing').removeAttr('disabled');
        }
      );
    }
  }
});

$(document).ready(
  function() {
    $$.Product.Ready();
  }
);