function addCommas(nStr) {
	nStr += '';
	x = nStr.split('.');
	x1 = x[0];
	x2 = x.length > 1 ? '.' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + ',' + '$2');
	}
	return x1 + x2;
}

function fnFilterColumn (table, filter, i) {
  $('#' + table).dataTable().fnFilter(
    filter,
    i,
    true,
    false
  );
}

function formatDate(convertDate) {
  var newDate = new Date(convertDate);
  newDay = newDate.getDate();
  newMonth = newDate.getMonth() + 1;
  newYear = newDate.getFullYear();
  if (newDay < 10) {
    newDay = '0' + newDay;
  }
  if (newMonth < 10) {
    newMonth = '0' + newMonth;
  }
  return newYear + '\\-' + newMonth + '\\-' + newDay;
}

$(document).ready(function() {

  $('.jui-datepicker').datepicker();
  $('.jui-button').button();

  $('#but-register').fadeTo(0, 0);
  $('#agree-to-conditions').change(function() {
    if ($('#agree-to-conditions').is(':checked')) {
      $('#but-register').stop().fadeTo(300, 1);
      $('#agree-to-conditions').siblings('a').attr('href', '/register');
    } else {
      $('#but-register').stop().fadeTo(300, 0);
      $('#agree-to-conditions').siblings('a').attr('href', '#');
    }
  });
  
  // Converts BC dates to something sortable by alphabetical order
  $('.bcDateConvert').each(function() {
    var timestamp = $(this).text();
    var timeDay = timestamp.substring(0, 2);
    var timeYear = timestamp.substring(7, 11);
    var timeMonth = timestamp.substring(3, 6);
    var timeTime = timestamp.substring(11);
    var myMonths = new Array();
    myMonths['Jan'] = '01';
    myMonths['Feb'] = '02';
    myMonths['Mar'] = '03';
    myMonths['Apr'] = '04';
    myMonths['May'] = '05';
    myMonths['Jun'] = '06';
    myMonths['Jul'] = '07';
    myMonths['Aug'] = '08';
    myMonths['Sep'] = '09';
    myMonths['Oct'] = '10';
    myMonths['Nov'] = '11';
    myMonths['Dec'] = '12';
    var newTimeMonth = myMonths[timeMonth];
    // $(this).text(timeYear + '-' + newTimeMonth + '-' + timeDay + ' ' + timeTime);
    $(this).text(timeYear + '-' + newTimeMonth + '-' + timeDay);
  });
  
  if ($('#ordertable').length) {
    $('#ordertable .ordertype').each(function() {
      if ($(this).html() !== 'Invoice') {
        $(this).parent().remove();
      }
    });
    $('#ordertable').dataTable({"aaSorting": [[ 1, "desc" ]], "bJQueryUI": true});
  }
  if ($('#quotetable').length) {
    $('#quotetable .ordertype').each(function() {
      if ($(this).html() !== 'Quote') {
        $(this).parent().remove();
      }
    });
    oTable = $('#quotetable').dataTable({"aaSorting": [[ 1, "desc" ]], "bJQueryUI": true});
  }
  if ($('#invoicetable').length) {
    $('#invoicetable').dataTable({"aaSorting": [[ 1, "desc" ]], "bJQueryUI": true});
  }
  if ($('#supporttable').length) {
    $('#supporttable').dataTable({"aaSorting": [[ 1, "desc" ]], "bJQueryUI": true});
  }
  
  $('.reset-filters').click(function() {
    $(this).siblings().val('');
    $(this).siblings().change();
  });
  
  $("#quote-status-filter").change( function() { fnFilterColumn('quotetable', $('#quote-status-filter').val(), 2); } );
  $("#order-status-filter").change( function() { fnFilterColumn('ordertable', $('#order-status-filter').val(), 2); } );
  
  $('.datatable-daterange').change(function() {
  
    var from = new Date($(this).parent().find('input:nth-child(1)').val());
    var to = new Date($(this).parent().find('input:nth-child(2)').val());
    
    from = from.getTime();
    to = to.getTime();
    
    var firstDay = formatDate(from);
    var lastDay = formatDate(to);
    
    var dateRegex = new String();
    var dayList = new String();
    var dayString = new String();
    var day = from;
    while (day < to) {
      day = day + 86400000;
      dayString = formatDate(day);
      dayList = dayList + '|' + dayString;
    }
    
    if (firstDay == 'NaN\\-NaN\\-NaN' && lastDay == 'NaN\\-NaN\\-NaN'){
      dateRegex = '';
    } else if (dayList.length > 0) {
      var dateRegex = '(' + firstDay + dayList + '|' + lastDay + ')';
    } else {
      var dateRegex = '(' + firstDay + '|' + lastDay + ')';
    }
    var tableId = $(this).parent().siblings('.dataTables_wrapper').find('.datatable').attr('id');
    fnFilterColumn(tableId, dateRegex, 1);
    
  });
  
  
  var amountowing = $('#amount-remittance').html();
  var ordertype = $('#ordertype').text();
  if (amountowing != '$0.00' && ordertype == 'Invoice') {
    $('#send-remittance').css('display', 'block');
  }
  if (ordertype == 'Quote') {
    $('#confirm-invoice').css('display', 'block');
  }
 
  $('#tcyes').click(function() {
    $('.tchide').css('display', 'block');
  });
  
  // new total for price
  var tally = 0;
  $('#product-totals .productitemcell').each(function() {
    var tallyme = $(this).html();
    tallyme = tallyme.replace(/\,/g,'');
    tallyme = tallyme.substr(1);
    tallyme = parseFloat(tallyme);
    tally += tallyme;
  });
  tally = Math.round(tally * 100) / 100;
  tally = tally.toFixed(2);
  tally = addCommas(tally);
  $('#order-grand-total').html('$' + tally);
  
  // new total for gst
  var tally = 0;
  $('#gst-totals .productitemcell').each(function() {
    var tallyme = $(this).html();
    tallyme = tallyme.replace(/\,/g,'');
    tallyme = tallyme.substr(1);
    tallyme = parseFloat(tallyme);
    tally += tallyme;
  });
  tally = Math.round(tally * 100) / 100;
  tally = tally.toFixed(2);
  tally = addCommas(tally);
  $('#order-grand-gst').html('$' + tally);
  
  $('#proceed-with-order').click(function() {
    
  });
  
  $('.jui-tip').each(function() {
    
    var idTag = $(this).attr('id');
    
    if ($(this).hasClass('jui-button')) {
      $(this).addClass('ui-icon');
      $(this).addClass('ui-icon-help');
    }
    
    var dialog = $('<div></div>').html(dialogs[idTag]).dialog({
      title: titles[idTag],
      autoOpen: false,
      modal: true,
      show: 'puff',
      hide: 'puff',
      buttons: {
        'Okay': function() {
          $(this).dialog('close');
        }
      }
    });
    
    $(this).click(function() {
      dialog.dialog('open');
      return false;
    });
    
  });

  $('.jui-confirm').each(function() {
    
    var idTag = $(this).attr('id');
    var hrefTag = $(this).attr('href');
    if (hrefTag == null) {
      var hrefTag = $(this).parent().attr('href');
    }
    
    var dialog = $('<div></div>').html(dialogs[idTag]).dialog({
      title: titles[idTag],
      autoOpen: false,
      modal: true,
      show: 'puff',
      hide: 'puff',
      buttons: {
        'Okay': function() {
          $(location).attr('href', hrefTag);
        },
        'Cancel': function() {
          $(this).dialog('close'); return false;
        }
      }
    });
    
    $(this).click(function() {
      dialog.dialog('open');
      return false;
    });
    
    
  });
  
  $('.jui-confirm-submit').each(function() {
    
    var idTag = $(this).attr('id');
    
    var dialog = $('<div></div>').html(dialogs[idTag]).dialog({
      title: titles[idTag],
      autoOpen: false,
      modal: true,
      show: 'puff',
      hide: 'puff',
      buttons: {
        'Okay': function() {
          $('#' + idTag).closest('form').submit();
        },
        'Cancel': function() {
          $(this).dialog('close'); return false;
        }
      }
    });
    
    $(this).click(function() {
      dialog.dialog('open');
      return false;
    });
    
  });
  
  $('#feedback-form').submit(function() {
    if ($('#RFMessage').val() !== '' && $('#RFFriend01').val() !== '') {
      $('#RFFullName').val($('#FirstName').val() + ' ' + $('#LastName').val());
      $('#RFEmailAddress').val($('#EmailAddress').val());
      $('#rfform').submit();
    }
  });
  
  $('.add-referfriend').click(function() {
    $(this).parent().parent().next().fadeIn();
  });
  
  $('#top-nav-center a').hover(function() {
    $(this).stop().animate({ color: '#F07800'}, 200);
  }, function() {
    $(this).stop().animate({ color: '#ffffff'}, 200);
  });
  
  $('#product-search-list').change(function() {
    $('.product-search-container').animate({ opacity: 0 });
    $('#products-loading').css('display', 'block');
    $('#CAT_ProductSearch').val($(this).val());
    $('#product-search-form').submit();
  });
  
  $('#product-search-button').click(function() {
    $('.product-search-container').animate({ opacity: 0 });
    $('#products-loading').css('display', 'block');
    $('#CAT_ProductSearch').val($('#product-search-input').val());
    $('#product-search-form').submit();
  });
  
  $('#product-search-range span').click(function() {
    $('.product-search-container').animate({ opacity: 0 });
    $('#products-loading').css('display', 'block');
    $('#CAT_ProductSearch').val($(this).text());
    $('#product-search-form').submit();
  });
  
  $('.domaths').each(function() {
    var mathString = $(this).text();
    mathString = mathString.replace(/\$/g, '');
    mathString = mathString.replace(/ /g, '');
    mathString = mathString.replace(/,/g, '');
    mathString = mathString.replace(/[\-,\+]/g, ' $&');
    mathArray = mathString.split(' ');
    mathVal = 0;
    for (x in mathArray) {
      symbol = mathArray[x].substr(0,1);
      number = mathArray[x].substr(1);
      if (symbol == '-') {
        number = parseFloat(number);
        mathVal = mathVal - number;
      } else if (symbol == '+') {
        number = parseFloat(number);
        mathVal = mathVal + number;
      } else {
        number = mathArray[x];
        number = parseFloat(number);
        mathVal = mathVal + number;
      }
    }
    if (mathVal < 0) {
      mathVal = mathVal * -1;
    }
    mathVal = mathVal.toFixed(2);
    $(this).text('$' + mathVal);
  });
  
  $('.productitemcell').each(function() {
    if ($(this).html() == '&nbsp;' || $(this).html() == 'Custom item -') {
      $(this).remove();
    }
  });
  
  if ($('#quote-widget-content').text() == 'No orders found.') {
    $('#quote-widget').css('display', 'none');
  }
  
});


function bodyLoaded() {
	document.getElementById('rollovertext').style.display = 'block';
	document.getElementById('rollovertext-webdesign').style.display = 'none';
	document.getElementById('rollovertext-onlineshop').style.display = 'none';
	document.getElementById('rollovertext-graphicdesign').style.display = 'none';
	document.getElementById('rollovertext-sms').style.display = 'none';
}

imgButton1=new Image();
imgButton1.src="/Images/template/imagenta2010/button-web-design-on.gif";

imgButton2=new Image();
imgButton2.src="/Images/template/imagenta2010/button-order-online-on.gif";

imgButton3=new Image();
imgButton3.src="/Images/template/imagenta2010/button-graphic-design-on.gif";

imgButton4=new Image();
imgButton4.src="/Images/template/imagenta2010/button-client-area-on.gif";

imgButton5=new Image();
imgButton5.src="/Images/template/imagenta2010/button-live-chat-on.gif";

imgButton5=new Image();
imgButton5.src="/Images/template/imagenta2010/button-mobile-hover.png";

function buttonWebDesignOn() {
	document.getElementById('rollovertext').style.display = 'none';
	document.getElementById('rollovertext-webdesign').style.display = 'block';
	document.getElementById('rollovertext-onlineshop').style.display = 'none';
	document.getElementById('rollovertext-graphicdesign').style.display = 'none';
	document.getElementById('rollovertext-sms').style.display = 'none';
	document.getElementById('button-web-design').src = '/Images/template/imagenta2010/button-web-design-on.gif';
}
function buttonWebDesignOff() {
	document.getElementById('button-web-design').src = '/Images/template/imagenta2010/button-web-design.gif';
	document.getElementById('rollovertext').style.display = 'block';
	document.getElementById('rollovertext-webdesign').style.display = 'none';
	document.getElementById('rollovertext-onlineshop').style.display = 'none';
	document.getElementById('rollovertext-graphicdesign').style.display = 'none';
	document.getElementById('rollovertext-sms').style.display = 'none';
}

function buttonOnlineShopOn() {
	document.getElementById('rollovertext').style.display = 'none';
	document.getElementById('rollovertext-webdesign').style.display = 'none';
	document.getElementById('rollovertext-onlineshop').style.display = 'block';
	document.getElementById('rollovertext-graphicdesign').style.display = 'none';
	document.getElementById('rollovertext-sms').style.display = 'none';
	document.getElementById('button-online-shop').src = '/Images/template/imagenta2010/button-order-online-on.gif';
}
function buttonOnlineShopOff() {
	document.getElementById('button-online-shop').src = '/Images/template/imagenta2010/button-order-online.gif';
	document.getElementById('rollovertext').style.display = 'block';
	document.getElementById('rollovertext-webdesign').style.display = 'none';
	document.getElementById('rollovertext-onlineshop').style.display = 'none';
	document.getElementById('rollovertext-graphicdesign').style.display = 'none';
	document.getElementById('rollovertext-sms').style.display = 'none';
}

function buttonGraphicDesignOn() {
	document.getElementById('rollovertext').style.display = 'none';
	document.getElementById('rollovertext-webdesign').style.display = 'none';
	document.getElementById('rollovertext-onlineshop').style.display = 'none';
	document.getElementById('rollovertext-graphicdesign').style.display = 'block';
	document.getElementById('rollovertext-sms').style.display = 'none';
	document.getElementById('button-graphic-design').src = '/Images/template/imagenta2010/button-graphic-design-on.gif';
}
function buttonGraphicDesignOff() {
	document.getElementById('button-graphic-design').src = '/Images/template/imagenta2010/button-graphic-design.gif';
	document.getElementById('rollovertext').style.display = 'block';
	document.getElementById('rollovertext-webdesign').style.display = 'none';
	document.getElementById('rollovertext-onlineshop').style.display = 'none';
	document.getElementById('rollovertext-graphicdesign').style.display = 'none';
	document.getElementById('rollovertext-sms').style.display = 'none';
}

function buttonSmsOn() {
	document.getElementById('rollovertext').style.display = 'none';
	document.getElementById('rollovertext-webdesign').style.display = 'none';
	document.getElementById('rollovertext-onlineshop').style.display = 'none';
	document.getElementById('rollovertext-graphicdesign').style.display = 'none';
	document.getElementById('rollovertext-sms').style.display = 'block';
	document.getElementById('button-sms').src = '/Images/template/imagenta2010/button-client-area-on.gif';
}
function buttonSmsOff() {
	document.getElementById('button-sms').src = '/Images/template/imagenta2010/button-client-area.gif';
	document.getElementById('rollovertext').style.display = 'block';
	document.getElementById('rollovertext-webdesign').style.display = 'none';
	document.getElementById('rollovertext-onlineshop').style.display = 'none';
	document.getElementById('rollovertext-graphicdesign').style.display = 'none';
	document.getElementById('rollovertext-sms').style.display = 'none';
}

// Client area buttons
function buttonClientHomeOn() {
	document.getElementById('button-client-home').src = '/Images/template/imagenta2010/but-client-home-on.png';
}
function buttonClientHomeOff() {
	document.getElementById('button-client-home').src = '/Images/template/imagenta2010/but-client-home.png';
}

function buttonLogoutOn() {
	document.getElementById('button-logout').src = '/Images/template/imagenta2010/but-logout-on.png';
}
function buttonLogoutOff() {
	document.getElementById('button-logout').src = '/Images/template/imagenta2010/but-logout.png';
}

function buttonHelpOn() {
	document.getElementById('button-help').src = '/Images/template/imagenta2010/but-help-on.png';
}
function buttonHelpOff() {
	document.getElementById('button-help').src = '/Images/template/imagenta2010/but-help.png';
}


function buttonLiveChatOn() {
	document.getElementById('button-live-chat').src = '/Images/template/imagenta2010/button-live-chat-on.gif';
}
function buttonLiveChatOff() {
	document.getElementById('button-live-chat').src = '/Images/template/imagenta2010/button-live-chat.gif';
	document.getElementById('rollovertext').style.display = 'block';
	document.getElementById('rollovertext-webdesign').style.display = 'none';
	document.getElementById('rollovertext-onlineshop').style.display = 'none';
	document.getElementById('rollovertext-graphicdesign').style.display = 'none';
	document.getElementById('rollovertext-sms').style.display = 'none';
}

function buttonMobileOn() {
	document.getElementById('img-mobile').src = '/Images/template/imagenta2010/button-mobile-hover.png';
}
function buttonMobileOff() {
	document.getElementById('img-mobile').src = '/Images/template/imagenta2010/button-mobile.png';
}

function bookmarksite(title,url){
if (window.sidebar) // firefox
	window.sidebar.addPanel(title, url, "");
else if(window.opera && window.print){ // opera
	var elem = document.createElement('a');
	elem.setAttribute('href',url);
	elem.setAttribute('title',title);
	elem.setAttribute('rel','sidebar');
	elem.click();
} 
else if(document.all)// ie
	window.external.AddFavorite(url, title);
  
}
