$(document).ready(
  function(){


    // left and right shadows for pageWrap
    $('#pageWrap')
      .wrapAll('<div id="stripe"><div id="pageWrapLeft"><div id="pageWrapRight"></div></div></div>');

	// hide msgPanel
    $("#msgPanel").click(
      function(){
        $(this).remove();
      }
    );

    // hide noticePanel
    $("#noticePanel").click(
      function(){
        $(this).remove();
      }
    );

    // zebra effect on table rows
    //$(".simple tr:even").addClass('even');

    // hiding details about receipts
    $('.receiptDetails').hide();
    $('.hidden').hide();

    // switch to closed details arrow
    $('.toggler').css("background-position","-30px 50%");

    // toggling receipt details
    $('td:has(span.toggler)').toggle(
      function(){
        $(this).find('span.toggler').css("background-position","0 50%");
        $(this).find('.receiptDetails').toggle();
        $(this).find('li a').css('cursor', 'pointer').click(
          function() {
            var urlAddr = $(this).attr('href');
            location.href = urlAddr;
            return false;
          });
      },
      function(){
        $(this).find('span.toggler').css("background-position","-30px 50%");
        $(this).find('.receiptDetails').toggle();
      }
    );

    // hilite returned items
    $('tr:has(span.returned)').find('*').css('color', '#ff0000');

    // tablesorter
    $('table.sortMe')
      .addClass('tablesorter')
      .tablesorter({
                     headers: {
                       0: {
                         sorter: false
                       },
                       1: {
                         sorter: false
                       }
                     },
                     widthFixed: true,
                     widgets: ['zebra']
                   })
      .tablesorterPager({
                          container: $(".pager"),
                          positionFixed: false
                        });

     // input elemet fixes
    $('input:text').css('border', '2px solid #b8bab8');
    $('input:password').css('border', '2px solid #b8bab8');
    $('select').css('border', '2px solid #b8bab8');
    $('textarea').css('border', '2px solid #b8bab8');
    $('input:image').css('border', '2px solid #b8bab8');
    $('input:button').css('border', '2px solid #b8bab8');
    $('input:file').css('border', '2px solid #b8bab8');
    $('textarea:disabled').css({
                                 'background-color' : '#fff',
                                 'color' : '#111111'
                               });
    $('fieldset.outer label input:text').css('display', 'block');
    $('fieldset.outer label input:password').css('display', 'block');
    $('fieldset.outer label input:file').css('display', 'block');
    $('fieldset.outer label textarea').css('display', 'block');

    // footer top border line simulation
    $('#footer').append('<div id="hr">&nbsp;</div>');

    //  pop-up
    $('div.popUp fieldset').wrap('<fieldset class="outer"></fieldset>');

    // showHide some form fields
    $('.showHide').toggle(
      function(){
        $(this).parent().css('border-color', '#204c80');
        $(this).find('input:checkbox').attr("checked","checked");
        $(this).parent().find('div.hidden').show();
      },
      function(){
        $(this).parent().css('border-color', '#204c80 #fff #fff #fff');
        $(this).find('input:checkbox').removeAttr("checked");
        $(this).parent().find('div.hidden').hide();
      })
      .parent().css('border-color', '#204c80 #fff #fff #fff');

    // add new item in receipt
    var i=1;
    $('table thead .add').parent().click(
      function(){
        var whereTo = $(this).parents('table').find('tbody');
        var newRow = $('table:has(thead .add)').find('tbody tr:last').clone();
        newRow.prependTo(whereTo);
        $(this).parents('table')
          .find('tbody tr:first').find('input')
          .attr('name',
                function(){
                  return this.name + i;
                }
               ).val('');
        i++;
        return false;
      }
    );

    // select all functionality
    $('table tfoot .selectAll').click(
      function(){
        $(this).parents('table')
          .find('input:checkbox').attr('checked', 'checked');
        return false;
      }
    );

    // unselect all functionality
    $('table tfoot .unselectAll').click(
      function(){
        $(this).parents('table')
          .find('input:checkbox').removeAttr('checked');
        return false;
      }
    );

    // form validations
    var formz = $('form.validateMe');
    jQuery.each(formz, function() {
      $(this)
        .validate();
    });


    // datepicker
    $('input.datePicker').datepicker();

    // simple toolTips
    $('.simpleToolTip').cluetip({
      splitTitle: '|',
      arrows: true,
      positionBy: 'mouse',
      sensitivity: 3, // hoverIntent
      interval: 200, // hoverIntent
      timeout: 500  // hoverIntent
      });

 // load tooltip content form hidden content inside div#tooltipsContainer
    $('.advancedToolTip')
      // transforming title attributes to rel
      .attr("rel",
            function(){
              return $(this).attr("title");
            }
           )
      // removing title attributes
      .removeAttr("title")
      .cluetip({
		    	  cluetipClass: 'jtip',
		    	  local: true,
                 arrows: true,
                 showTitle: false,
                 sticky: false,
                 mouseOutClose: true,
                 positionBy: 'mouse',
                 width: 310,
                 topOffset: 7,
                 leftOffset: 15,
                 sensitivity: 3, // hoverIntent
                 interval: 200, // hoverIntent
                 timeout: 500  // hoverIntent
      });
    
 // load tooltip content form hidden content inside div#tooltipsContainer
    $('.itemToolTip')
      // transforming title attributes to rel
      .attr("rel",
            function(){
              return $(this).attr("title");
            }
           )
      // removing title attributes
      .removeAttr("title")
      .cluetip({
		    	  cluetipClass: 'jtip',
		    	  local: true,
                 arrows: true,
                 showTitle: false,
                 sticky: false,
                 mouseOutClose: true,
                 positionBy: 'mouse',
                 width: 150,
                 height: 150,
                 topOffset: 7,
                 leftOffset: 15,
                 sensitivity: 3, // hoverIntent
                 interval: 200, // hoverIntent
                 timeout: 500  // hoverIntent
      });

 // hide noticePanel
    $("#mySubtotal").change(
  	      function(){
  	    	  var total = 0;
  	    	  var subTotalString = $(this).val();
  	    	  var subtotal = parseFloat(subTotalString.replace(/[^0-9\.]+/g,""));

  	    	  var taxString = $(this).parents('fieldset').find('#myTax').val();
	    	  var tax = parseFloat(taxString.replace(/[^0-9\.]+/g,""));

	    	  var discountString = $(this).parents('fieldset').find('#myDiscount').val();
  	    	  var discount = parseFloat(discountString.replace(/[^0-9\.]+/g,""));

	  	      if (discount < 0)
	  	    	  total = subtotal + tax + discount;
	  	      else
	  	    	  total = subtotal + tax - discount;

  	    	  $(this).parents('fieldset').find('#myTotal').val(total);
  	    	  $(this).parents('fieldset').find('#myTotal').format({format:"#,###.00", locale:"us"});
  	    	  $(this).parents('fieldset').find('#myTax').format({format:"#,###.00", locale:"us"});
  	    	  $(this).parents('fieldset').find('#myDiscount').format({format:"#,###.00", locale:"us"});
	    	  $(this).format({format:"#,###.00", locale:"us"});

  	      }
      	);

    $("#myTax").change(
  	      function(){
  	    	  var total = 0;
  	    	  var taxString = $(this).val();
  	    	  var tax = parseFloat(taxString.replace(/[^0-9\.]+/g,""));

  	    	  var subTotalString = $(this).parents('fieldset').find('#mySubtotal').val();
  	    	  var subtotal = parseFloat(subTotalString.replace(/[^0-9\.]+/g,""));

  	    	  var discountString = $(this).parents('fieldset').find('#myDiscount').val();
	    	  var discount = parseFloat(discountString.replace(/[^0-9\.]+/g,""));

	    	  if (discount < 0)
    	    	  total = subtotal + tax + discount;
    	      else
    	    	  total = subtotal + tax - discount;

  	    	  $(this).parents('fieldset').find('#myTotal').val(total);
  	    	  $(this).parents('fieldset').find('#myTotal').format({format:"#,###.00", locale:"us"});
  	    	  $(this).parents('fieldset').find('#mySubtotal').format({format:"#,###.00", locale:"us"});
  	    	  $(this).parents('fieldset').find('#myDiscount').format({format:"#,###.00", locale:"us"});

  	    	  $(this).format({format:"#,###.00", locale:"us"});
  	      }
      	);

    $("#myDiscount").change(
  	      function(){
  	    	  var total = 0;
  	    	  var discountString = $(this).val();
  	    	  var discount = parseFloat(discountString.replace(/[^0-9\.]+/g,""));

  	    	  var subTotalString = $(this).parents('fieldset').find('#mySubtotal').val();
  	    	  var subtotal = parseFloat(subTotalString.replace(/[^0-9\.]+/g,""));

  	    	  var taxString = $(this).parents('fieldset').find('#myTax').val();
    	      var tax = parseFloat(taxString.replace(/[^0-9\.]+/g,""));

    	      if (discount < 0)
    	    	  total = subtotal + tax + discount;
    	      else
    	    	  total = subtotal + tax - discount;

  	    	  $(this).parents('fieldset').find('#myTotal').val(total);
  	    	  $(this).parents('fieldset').find('#myTotal').format({format:"#,###.00", locale:"us"});
  	    	  $(this).parents('fieldset').find('#mySubtotal').format({format:"#,###.00", locale:"us"});
  	    	  $(this).parents('fieldset').find('#myTax').format({format:"#,###.00", locale:"us"});

  	    	  $(this).format({format:"#,###.00", locale:"us"});
  	      }
      	);

  $("#myTotal").change(
    	      function(){
    	    	  var total = 0;
    	    	  var totalString = $(this).val();
    	    	  var newtotal = parseFloat(totalString.replace(/[^0-9\.]+/g,""));

    	    	  var taxString = $(this).parents('fieldset').find('#myTax').val();
    	    	  var tax = parseFloat(taxString.replace(/[^0-9\.]+/g,""));

    	    	  var subTotalString = $(this).parents('fieldset').find('#mySubtotal').val();
    	    	  var subtotal = parseFloat(subTotalString.replace(/[^0-9\.]+/g,""));

    	    	  var discountString = $(this).parents('fieldset').find('#myDiscount').val();
      	    	  var discount = parseFloat(discountString.replace(/[^0-9\.]+/g,""));

      	    	  $(this).parents('fieldset').find('#myTax').format({format:"#,###.00", locale:"us"});
	  	    	  $(this).parents('fieldset').find('#mySubtotal').format({format:"#,###.00", locale:"us"});
	  	    	  $(this).parents('fieldset').find('#myDiscount').format({format:"#,###.00", locale:"us"});
	  	    	  $(this).format({format:"#,###.00", locale:"us"});

	  	    	  if (discount < 0)
	    	    	  total = subtotal + tax + discount;
	    	      else
	    	    	  total = subtotal + tax - discount;

	  	    	  if (newtotal != total)
	  	    	  {
	  	    		  alert("WARNING: The subtotal and tax values do not match the total amount.");
	  	    	  }

    	      }
        	);

  $("#myAcct").change(function () {
      var str = "";
      $("#myAcct option:selected").each(function () {
            str += $(this).text();
            $('#myAcctName').val(str);
            if (str != 'Select From List')
            {
            	$('#loyaltyInfo').show();
                 
            }
            else
            {
            	$('#loyaltyInfo').hide();
        	}
          });
      
    });


    //$("#myMerchant")
    //  .parents('fieldset')
    //  .find('input[name^="my"]').val('');
    $("#myMerchant")
      .autocomplete(merchants,
    		  		{
    	  			  minChars: 0,
                      width: 310,
                      matchContains: true,
                      mustMatch: false,
                      autoFill: true,
                      formatItem: function(row, i, max) {
                        return row.merchant;
                      }
                    })
      .focus(function(){
               if ( $(this).val() == 'Please select...' ){
                 $(this).val('');
               }
             })
      .result(function(event, data, formatted){
                if (data){
	            	$(this).parents('fieldset').find('#myID').val(data.id);
	            	$(this).parents('fieldset').find('#myAddr').val(data.address);
	                $(this).parents('fieldset').find('#myAddr2').val(data.address2);
                  $(this).parents('fieldset').find('#myCity').val(data.city);
                  $(this).parents('fieldset').find('#myState').val(data.state);
                  $(this).parents('fieldset').find('#myZip').val(data.zip);
                  $(this).parents('fieldset').find('#myPhone').val(data.phone);
                }
              });

  });
