9// JavaScript Document
var ewpath = '/engineware/';
//var ewpath = '/ecobulb/engineware/';  /*overwrite for when I am developing this locally */
var prods;
var fgt=0;
var crit = '';
var region = false; /* region specific data here, like country name, country code, exchange rate */

var can_checkout;

function logger(msg) {
  if (typeof console !== 'undefined') {
    console.log(msg);
  }
}

function jumpToHash(hash) {
	if (hash=='shippingdetails' && !can_checkout)
	{
		alert('There are no products in you cart, click here to continue shopping');
		hash = 'products';
	}
  logger('jump to hash for '+hash);
 /*  window.location.hash = hash; */
  pageload(hash);
}

  // PageLoad function
  // This function is called when:
  // 1. after calling $.historyInit();
  // 2. after calling $.historyLoad();
  // 3. after pushing "Go Back" button of a browser
  function pageload(hash) {
    logger('page load for '+hash);
    // hash doesn't contain the first # character.
    if (!hash && window.location.hash) {
      hash = window.location.hash;
    }
    if(hash) {
      // restore ajax loaded state
      if (hash.substr(0,8) == 'products') {
        changeProgressBar();
        if (hash.length == 8) {
          product_list('all');
        }else{
          product_list(hash.substr(9));
        }
        return;
      }
      switch(hash) {
        case 'products':
			/* this will never happen because of the IF statement above?!? */
          product_list('all');
					
          changeProgressBar();
          break;
        case 'confirm-order':
          changeProgressBar(2);
          confirm_order();
          break;
        case 'payment-type':
          changeProgressBar(3);
          payment_type_select();
          break;
        case 'checkout':
        case 'shippingdetails':
          changeProgressBar(1);
          checkout(); // shipping details page
          break;
        case 'payment-directcredit':
          changeProgressBar(4);
          place_order2('dc');
          break;
        case 'payment-creditcard':
          changeProgressBar(4);
          payCreditCard();
          break;
        case 'cart':
          changeProgressBar();
          view_cart(null);
          break;
        case 'success':
          changeProgressBar();
		  show_success_message();
          break;
      }
    } else {
      changeProgressBar();
        product_list('all');
        cart_detail();
    }
  }

$(function(){
  $(window).bind('scroll',function (e) {
    var windowbottom = getScrollY()  + getWindowHeight();
    var holderheight = $('#content').height();
    var holderoffset = $('#content').offset();
    var boxheight = $('#mycart').height();
    var boxoffset = $('#mycart').offset();
    var holderbottom = holderheight + holderoffset.top;
    var boxpad = 0;
    if (windowbottom > holderbottom) {
      boxpad = holderheight - (boxoffset.top - holderoffset.top);
      boxpad -= boxheight + 20;
    }else if(windowbottom < boxoffset.top) {
      boxpad = 0;
    }else{
      boxpad = windowbottom - (boxheight + 20 + 250);
      boxpad -= boxoffset.top;
    }

		if (boxpad<0)
			boxpad = 0;
			
		boxpad = boxpad+'px';

    $('#mycart').stop().animate({paddingTop: boxpad},600);
  }).trigger('scroll');
	
	
	
	/* set the session and get country details before loading any products etc in */
	$.getJSON(ewpath+'s/order/regionalSettings',{country_code : country_code},function(data){
		region = data; //save the regional data
		$('#country_name').html(region.country_name);
		$(document).attr('title',"Ecobulb&reg; "+region.country_name+" Store | energy saving light bulbs");
		cart_detail();
		changeProgressBar();
		$.historyInit(pageload);
	});
	
	
  // set onlick event for buttons
  $("a[rel='history']").live('click', function(){
    var hash = this.href;
    hash = hash.replace(/^.*#/, '');
    // moves to a new page.
    // pageload is called at once.
    $.historyLoad(hash);
    return false;
  });
  $('#tosClose').click(function () {
    $('#tosPopUp, #tosOverlay').hide();
    return false;
  });
  $('#tosView,#tosLink').click(function () {
    $('#tosPopUp, #tosOverlay').show();
    return false;
  });
  StuffThatNeedsToBeLoaded();

});

function StuffThatNeedsToBeLoaded() {
  // how often will a new state be added that this has to be done dynamically,
  // even if they did change, whats wrong with spitting it out at the html stage,
  // rather than wasting ANOTHER request

/*  $.getJSON(ewpath+'s/order/state_list/', function(d){
    var h = '<select id="state" name="state"><option value="">select state here</option>';
    $.each(d, function(i, n) {
        h += '<option value="'+n.State+'">'+n.State+'</option>';
    });
    h+= '</select> *';
    $('#state').html(h);
  }); */
  $('#confirmNext').click(function () {
    if (!$('#tosConfirm:checked').length) {
      alert('You must agree to our terms and conditions before proceeding');
      return false;
    }
    jumpToHash('payment-type');
    return false;
  });
  $('#paymentTypeCCNext').click(function () {
    jumpToHash('payment-creditcard');
    return false;
  });
  $('#paymentTypeDCNext').click(function () {
    jumpToHash('payment-directcredit');
    return false;
  });
}
function hide_all(){
    $('#after_payment, #purchase_success, #top1, #postal_form, #credit_card, #cart, #cart_s, #credit_card_detail, #featured-products, .fakepage').hide();
}
function more(id){
  $('#featured-products .sd').show();
  $('#sd'+id).hide();
  $('#featured-products .des').hide();
  $('#des'+id).show(500);
}


/* this hash will check if a payment has happened recently (somehow?) and then show a message if appropriate */
function show_success_message()
{
	hide_all();
	$('#purchase_success').show();
}


function product_list(c){
    hide_all();
		cart_detail();
    $('#featured-products').show();
    $('#top1, #cart_s').show();
    $('#loading').slideDown();
  var h = '<table class="featured-products"><tr style="background-color:#e6e6e6;"><td colspan="4"><div style="float: right; margin-right: 5px; visibility: visible;" >Sort by: <select id="criteria"><option>all</option><option>bulbs</option><option>screw fitting</option><option>bayonet fitting</option><option>wattage</option><option>downlights</option><option>accessories</option></select></div></td></tr>';
  if(null==c || c=='all'){
        $.getJSON(ewpath+'s/order/rankproducts',function(d){
          $('#loading').slideUp();
             prods = d;
            for(x in d){
                if(d[x].h=='1'){
                   if(null==d[x].im || d[x].im=='') {
                      var image = 'Image available soon';
                   }else{
                      var image = '<a  class="box" href="'+d[x].im+'" ><img src="'+d[x].im+'" alt="enlarge image" title="enlarge image" height="85" class="thumbnail"/></a>';
                    h += '<tr ><td width="87" valign="middle" align="center" class="plbl">'+image+'</td>'+
                    '<td width="147" valign="top" class="plbl"><span class="wattage">'+d[x].n+'</span><span class="screw-type"> '+d[x].type+'</span> <br />'+
                    '<span class="stock-warning"><strong>'+d[x].stn+' </strong></span><span class="specs"><strong><br />'+
                    ' Equivalent wattage:</strong> '+d[x].ewat+' <br />'+
                    '<strong>Quantity per carton:</strong> '+d[x].carton+' <br />'+
                    ' <strong>Cost per bulb:</strong> '+region.dollar_prefix+'$'+d[x].up+' ea</span><br /><br /></td>'+
                    '<td width="202" valign="top" class="plbl"><span class="info-title">Information: </span><br />'+
                    '<span class="info-list" "><div id="sd'+d[x].i+'" class="sd">'+d[x].sd+'...<br /><a href="#" style="text-decoration:none;" onclick="more('+d[x].i+'); return false;"> [ more ]</a></div><div id="des'+d[x].i+'" class="des">'+d[x].d+'</div>'+
                    '</span><br /></td>'+
                    '<td width="106" align="right" class="plbl"><strong>Carton:</strong> $'+d[x].p+''+
                    '<p class="space"><strong>Quantity:</strong>'+
                    '<input type="text" class="quantity" maxlength="5" size="3" name="quantity" id="quan'+d[x].i+'" value="1" />'+
                    '</p>'+
                    '<p class="space">'+
                    '<input type="hidden" name="add" value="10"/>'+
                    '<input type="hidden" name="colour" value="0"/>'+
                    '<input type="hidden" name="size" value="0"/>'+
                    '<button onclick="send_order('+d[x].i+');" name="buy-now" src="/images/btn-add-to-cart.gif" class="cart-button">add to cart </button>'+
                    '</p></td></tr>';
                  }
                }
            }
        $('#featured-products').html(h+'</table>');
        $('#featured-products .des').hide();
        $('a').filter('.box').lightBox();
        $('#criteria').val(c).change(function () {
          jumpToHash('products-'+$(this).val());
        });

      });
  }else{
    $.getJSON(ewpath+'s/order/get_products',function(d){
      $('#loading').slideUp();
      prods = d;
      for(x in d){
       if(c=='bulbs'){
             if(d[x].h=='0' && d[x].c=='1'){
                if(null==d[x].im || d[x].im=='')
                      var image = 'Image available soon';
                else
                      var image = '<a  class="box" href="'+d[x].im+'" ><img src="'+d[x].im+'" alt="enlarge image" title="enlarge image" height="85" class="thumbnail"/></a>';
                h += '<tr ><td width="87" valign="middle" align="center" class="plbl">'+image+'</td>'+
                '<td width="147" valign="top" class="plbl"><span class="wattage">'+d[x].n+'</span><span class="screw-type"> '+d[x].type+'</span> <br />'+
                '<span class="stock-warning"><strong>'+d[x].stn+' </strong></span><span class="specs"><strong><br />'+
                 ' Equivalent wattage:</strong> '+d[x].ewat+' <br />'+
                  '<strong>Quantity per carton:</strong> '+d[x].carton+' <br />'+
                 ' <strong>Cost per bulb:</strong> AU$'+d[x].up+' ea</span><br /><br /></td>'+
                '<td width="202" valign="top" class="plbl"><span class="info-title">Information: </span><br />'+
                '<span class="info-list" "><div id="sd'+d[x].i+'" class="sd">'+d[x].sd+'...<br /><a href="#" style="text-decoration:none;" onclick="more('+d[x].i+'); return false;"> [ more ]</a></div><div id="des'+d[x].i+'" class="des">'+d[x].d+'</div>'+
                '</span><br /></td>'+
                '<td width="106" align="right" class="plbl"><strong>Carton:</strong> $'+d[x].p+''+
                '<p class="space"><strong>Quantity:</strong>'+
                    '<input type="text" class="quantity" maxlength="5" size="3" name="quantity" id="quan'+d[x].i+'" value="1" />'+
                '</p>'+
                '<p class="space">'+
                 '<input type="hidden" name="add" value="10"/>'+
                  '<input type="hidden" name="colour" value="0"/>'+
                  '<input type="hidden" name="size" value="0"/>'+
                  '<button onclick="send_order('+d[x].i+');" name="buy-now" src="/images/btn-add-to-cart.gif" class="cart-button">add to cart </button>'+
                '</p></td></tr>';
             }
         }else if(c=='downlights'){
             if(d[x].h=='0' && d[x].c=='2'){
                if(null==d[x].im || d[x].im=='')
                      var image = 'Image available soon';
                else
                      var image = '<a  class="box" href="'+d[x].im+'" ><img src="'+d[x].im+'" alt="enlarge image" title="enlarge image" height="85" class="thumbnail"/></a>';
                h += '<tr ><td width="87" valign="middle" align="center" class="plbl">'+image+'</td>'+
                '<td width="147" valign="top" class="plbl"><span class="wattage">'+d[x].n+'</span><span class="screw-type"> '+d[x].type+'</span> <br />'+
                '<span class="stock-warning"><strong>'+d[x].stn+' </strong></span><span class="specs"><strong><br />'+
                 ' Equivalent wattage:</strong> '+d[x].ewat+' <br />'+
                  '<strong>Quantity per carton:</strong> '+d[x].carton+' <br />'+
                 ' <strong>Cost per bulb:</strong> AU$'+d[x].up+' ea</span><br /><br /></td>'+
                '<td width="202" valign="top" class="plbl"><span class="info-title">Information: </span><br />'+
                '<span class="info-list" "><div id="sd'+d[x].i+'" class="sd">'+d[x].sd+'...<br /><a href="#" style="text-decoration:none;" onclick="more('+d[x].i+'); return false;"> [ more ]</a></div><div id="des'+d[x].i+'" class="des">'+d[x].d+'</div>'+
                '</span><br /></td>'+
                '<td width="106" align="right" class="plbl"><strong>Carton:</strong> $'+d[x].p+''+
                '<p class="space"><strong>Quantity:</strong>'+
                    '<input type="text" class="quantity" maxlength="5" size="3" name="quantity" id="quan'+d[x].i+'" value="1" />'+
                '</p>'+
                '<p class="space">'+
                 '<input type="hidden" name="add" value="10"/>'+
                  '<input type="hidden" name="colour" value="0"/>'+
                  '<input type="hidden" name="size" value="0"/>'+
                  '<button onclick="send_order('+d[x].i+');" name="buy-now" src="/images/btn-add-to-cart.gif" class="cart-button">add to cart </button>'+
                '</p></td></tr>';
             }
         }else if(c=='accessories'){
             if(d[x].h=='0' && d[x].c=='3'){
                if(null==d[x].im || d[x].im=='')
                      var image = 'Image available soon';
                else
                      var image = '<a  class="box" href="'+d[x].im+'" ><img src="'+d[x].im+'" alt="enlarge image" title="enlarge image" height="85" class="thumbnail"/></a>';
                h += '<tr ><td width="87" valign="middle" align="center" class="plbl">'+image+'</td>'+
                '<td width="147" valign="top" class="plbl"><span class="wattage">'+d[x].n+'</span><span class="screw-type"> '+d[x].type+'</span> <br />'+
                '<span class="stock-warning"><strong>'+d[x].stn+' </strong></span><span class="specs"><strong><br />'+
                 ' Equivalent wattage:</strong> '+d[x].ewat+' <br />'+
                  '<strong>Quantity per carton:</strong> '+d[x].carton+' <br />'+
                 ' <strong>Cost per bulb:</strong> AU$'+d[x].up+' ea</span><br /><br /></td>'+
                '<td width="202" valign="top" class="plbl"><span class="info-title">Information: </span><br />'+
                '<span class="info-list" "><div id="sd'+d[x].i+'" class="sd">'+d[x].sd+'...<br /><a href="#" style="text-decoration:none;" onclick="more('+d[x].i+'); return false;"> [ more ]</a></div><div id="des'+d[x].i+'" class="des">'+d[x].d+'</div>'+
                '</span><br /></td>'+
                '<td width="106" align="right" class="plbl"><strong>Carton:</strong> $'+d[x].p+''+
                '<p class="space"><strong>Quantity:</strong>'+
                    '<input type="text" class="quantity" maxlength="5" size="3" name="quantity" id="quan'+d[x].i+'" value="1" />'+
                '</p>'+
                '<p class="space">'+
                 '<input type="hidden" name="add" value="10"/>'+
                  '<input type="hidden" name="colour" value="0"/>'+
                  '<input type="hidden" name="size" value="0"/>'+
                  '<button onclick="send_order('+d[x].i+');" name="buy-now" src="/images/btn-add-to-cart.gif" class="cart-button">add to cart </button>'+
                '</p></td></tr>';
             }
         }else if(c=='screw fitting'){
             if(d[x].h=='0' && d[x].type=='Screw'){
                if(null==d[x].im || d[x].im=='')
                      var image = 'Image available soon';
                else
                      var image = '<a  class="box" href="'+d[x].im+'" ><img src="'+d[x].im+'" alt="enlarge image" title="enlarge image" height="85" class="thumbnail"/></a>';
                h += '<tr ><td width="87" valign="middle" align="center" class="plbl">'+image+'</td>'+
                '<td width="147" valign="top" class="plbl"><span class="wattage">'+d[x].n+'</span><span class="screw-type"> '+d[x].type+'</span> <br />'+
                '<span class="stock-warning"><strong>'+d[x].stn+' </strong></span><span class="specs"><strong><br />'+
                 ' Equivalent wattage:</strong> '+d[x].ewat+' <br />'+
                  '<strong>Quantity per carton:</strong> '+d[x].carton+' <br />'+
                 ' <strong>Cost per bulb:</strong> AU$'+d[x].up+' ea</span><br /><br /></td>'+
                '<td width="202" valign="top" class="plbl"><span class="info-title">Information: </span><br />'+
                '<span class="info-list" "><div id="sd'+d[x].i+'" class="sd">'+d[x].sd+'...<br /><a href="#" style="text-decoration:none;" onclick="more('+d[x].i+'); return false;"> [ more ]</a></div><div id="des'+d[x].i+'" class="des">'+d[x].d+'</div>'+
                '</span><br /></td>'+
                '<td width="106" align="right" class="plbl"><strong>Carton:</strong> $'+d[x].p+''+
                '<p class="space"><strong>Quantity:</strong>'+
                    '<input type="text" class="quantity" maxlength="5" size="3" name="quantity" id="quan'+d[x].i+'" value="1" />'+
                '</p>'+
                '<p class="space">'+
                 '<input type="hidden" name="add" value="10"/>'+
                  '<input type="hidden" name="colour" value="0"/>'+
                  '<input type="hidden" name="size" value="0"/>'+
                  '<button onclick="send_order('+d[x].i+');" name="buy-now" src="/images/btn-add-to-cart.gif" class="cart-button">add to cart </button>'+
                '</p></td></tr>';
             }
         }else if(c=='bayonet fitting'){
             if(d[x].h=='0' && d[x].type=='Bayonet'){
                if(null==d[x].im || d[x].im=='')
                      var image = 'Image available soon';
                else
                      var image = '<a  class="box" href="'+d[x].im+'" ><img src="'+d[x].im+'" alt="enlarge image" title="enlarge image" height="85" class="thumbnail"/></a>';
                h += '<tr ><td width="87" valign="middle" align="center" class="plbl">'+image+'</td>'+
                '<td width="147" valign="top" class="plbl"><span class="wattage">'+d[x].n+'</span><span class="screw-type"> '+d[x].type+'</span> <br />'+
                '<span class="stock-warning"><strong>'+d[x].stn+' </strong></span><span class="specs"><strong><br />'+
                 ' Equivalent wattage:</strong> '+d[x].ewat+' <br />'+
                  '<strong>Quantity per carton:</strong> '+d[x].carton+' <br />'+
                 ' <strong>Cost per bulb:</strong> AU$'+d[x].up+' ea</span><br /><br /></td>'+
                '<td width="202" valign="top" class="plbl"><span class="info-title">Information: </span><br />'+
                '<span class="info-list" "><div id="sd'+d[x].i+'" class="sd">'+d[x].sd+'...<br /><a href="#" style="text-decoration:none;" onclick="more('+d[x].i+'); return false;"> [ more ]</a></div><div id="des'+d[x].i+'" class="des">'+d[x].d+'</div>'+
                '</span><br /></td>'+
                '<td width="106" align="right" class="plbl"><strong>Carton:</strong> $'+d[x].p+''+
                '<p class="space"><strong>Quantity:</strong>'+
                    '<input type="text" class="quantity" maxlength="5" size="3" name="quantity" id="quan'+d[x].i+'" value="1" />'+
                '</p>'+
                '<p class="space">'+
                 '<input type="hidden" name="add" value="10"/>'+
                  '<input type="hidden" name="colour" value="0"/>'+
                  '<input type="hidden" name="size" value="0"/>'+
                  '<button onclick="send_order('+d[x].i+');" name="buy-now" src="/images/btn-add-to-cart.gif" class="cart-button">add to cart </button>'+
                '</p></td></tr>';
             }
         }else{
             if(d[x].h=='0' && d[x].wattage!='' && d[x].c!='3'){
                if(null==d[x].im || d[x].im=='')
                      var image = 'Image available soon';
                else
                      var image = '<a  class="box" href="'+d[x].im+'" ><img src="'+d[x].im+'" alt="enlarge image" title="enlarge image" height="85" class="thumbnail"/></a>';
                h += '<tr ><td width="87" valign="middle" align="center" class="plbl">'+image+'</td>'+
                '<td width="147" valign="top" class="plbl"><span class="wattage">'+d[x].n+'</span><span class="screw-type"> '+d[x].type+'</span> <br />'+
                '<span class="stock-warning"><strong>'+d[x].stn+' </strong></span><span class="specs"><strong><br />'+
                 ' Equivalent wattage:</strong> '+d[x].ewat+' <br />'+
                  '<strong>Quantity per carton:</strong> '+d[x].carton+' <br />'+
                 ' <strong>Cost per bulb:</strong> AU$'+d[x].up+' ea</span><br /><br /></td>'+
                '<td width="202" valign="top" class="plbl"><span class="info-title">Information: </span><br />'+
                '<span class="info-list" "><div id="sd'+d[x].i+'" class="sd">'+d[x].sd+'...<br /><a href="#" style="text-decoration:none;" onclick="more('+d[x].i+'); return false;"> [ more ]</a></div><div id="des'+d[x].i+'" class="des">'+d[x].d+'</div>'+
                '</span><br /></td>'+
                '<td width="106" align="right" class="plbl"><strong>Carton:</strong> $'+d[x].p+''+
                '<p class="space"><strong>Quantity:</strong>'+
                    '<input type="text" class="quantity" maxlength="5" size="3" name="quantity" id="quan'+d[x].i+'" value="1" />'+
                '</p>'+
                '<p class="space">'+
                 '<input type="hidden" name="add" value="10"/>'+
                  '<input type="hidden" name="colour" value="0"/>'+
                  '<input type="hidden" name="size" value="0"/>'+
                  '<button onclick="send_order('+d[x].i+');" name="buy-now" src="/images/btn-add-to-cart.gif" class="cart-button">add to cart </button>'+
                '</p></td></tr>';
            }
          }
      }

      $('#featured-products').html(h+'</table>');
      $('#featured-products .des').hide();
      $('a').filter('.box').lightBox();
      $('#criteria').val(c).change(function () {
          jumpToHash('products-'+$(this).val());
        });
    });
  }


}
function relist(c){
  crit = c;
  product_list(c);

}
function product_detail(id){
    for(x in prods){
       if(x==id){
          var h = prods[x].d;
       }
    }
    $('#des'+id).html("<br />"+h);
}

function send_order(id){
  var q = $('#quan'+id).val();
  //$.get(ewpath+'s/order/s',{action:'place_order', quantity:q, pid:id, country:country}, function(d){
    $('#loading').slideDown();
  $.get(ewpath+'s/order/place_order',{quantity:q, pid:id}, function(d){

      cart_detail();
  });
}

function cart_detail(){
  if (!$('#loading:visible').length) {
    $('#loading').slideDown();
  }
  var h='';
  var freight = null;
  $('#cart_s').html('').show(300);
  //$.getJSON(ewpath+'s/order/s',{action:'cart_detail'}, function(data){

  $.getJSON(ewpath+'s/order/cart_detail', function(data){
    $('#loading').slideUp();
      if(null==data){
        $('#cart_s').hide();
      }else{
        var total=0;
        var ci = data;
        h = '<div class="cart_title" style="margin-top: 25px;"><div class="c3">Sub</div><div class="c2"></div><div class="c1">Product</div></div>';
        for(x in ci){
           //total += parseFloat(ci[x].p*ci[x].q);
            var st = parseFloat(ci[x].p*ci[x].q);
            total += st;
           //alert('total:'+total+' , price:'+ci[x].p+', quantity:'+ci[x].q+', name:'+name);
           var name = (ci[x].n).substr(0, 11);
           h += '<div class="clear-block"><div class="c3">'+st.toFixed(2)+'</div><div class="c2" style="width:15px">'+ci[x].q+'x </div><div class="c1">'+name+'</div></div>';
        }
        h += '<br /><table id="cart_table1" style="width:130px"><tr><td id="dash1"><div id="s_t" style="float:right;">Total: '+region.dollar_prefix+formatCurrency(total)+'</div><br /><button class="cart-button-s" clear:left;" onclick="jumpToHash(\'cart\')">Cart</button>&nbsp;<button class="cart-button-s"   onclick="jumpToHash(\'shippingdetails\')">Checkout</button> </td></tr></table>';
        $('#cart_s').html(h);
				if (total==0)
				{
					can_checkout = false;
				}
				else
				{
					can_checkout = true;
				}
      }
  });
}

function view_cart(freight){
  $('#cart').html('').show();
  $('#mycart').css("padding-top", "138px");
  $('#featured-products').hide();

  var html='<br /><a href="#products" rel="history">Carry on Shopping</a><h3>Cart Detail</h3><br /><div id="update_cart_form" name="update_cart_form"><div class="cart_title"><div class="ct1">Name</div><div class="ct2">Price</div><div class="ct3">Quantity</div><div class="ct33">Subtotal</div><div class="ct4">Photo</div>';
  if (null === freight)
    html += '<div class="ct5">Remove</div>';
  html += '</div><br />';

  var row='';
  var count=0;
  var inner_count=0;
  var total = 0;
  //$.getJSON(ewpath+'s/order/s',{action:'view_cart_2'}, function(cart_info){
    $('#loading').slideDown();
  $.getJSON(ewpath+'s/order/cart_detail', function(cart_info){
    $('#loading').slideUp();
    if(null==cart_info){
      $('#cart_detail').html('<br />There is nothing in your Cart at this time.');
      return false;
    }
    for(x in cart_info){
      var st = parseFloat(cart_info[x].p*cart_info[x].q);
      total += st;
      var photo = '<img src="'+cart_info[x].im+'" height="80px" />'; //<div class="ct3">'+cart_info[x].q+'</div>
      html += '<br /><div id="item'+cart_info[x].h+'" class="eshopitem"><div class="ct1"><input name="skuid[]" type="hidden" value="'+cart_info[x].h+'">'+cart_info[x].n+'</div><div class="ct2" id= "cpp'+cart_info[x].h+'">'+cart_info[x].p+'</div><div class="ct3">';
      if (null === freight) {
        html += '<input type="text" size="3" name="quan[]" id="qty'+cart_info[x].h+'" value="'+cart_info[x].q+'" onkeyup="change('+cart_info[x].h+');"/>';
      }else{
        html += cart_info[x].q;
      }
      html += '</div><div class="ct33" id="st'+cart_info[x].h+'">'+st.toFixed(2)+'</div><div class="ct4" >'+photo+'</div><div class="ct5" id="bd'+cart_info[x].h+'">';
      if (null === freight)
        html += '<input type="checkbox" name="rev[]" value="'+cart_info[x].h+'" onclick="remove('+cart_info[x].h+');">';
      html += '</div></div><div class="clear_both"></div><br /><br />';
    }

    if(null===freight){
      html += '<br /><br /><br /><br /><br /><div class="update_mess" style="display: none">The cart has been updated.</div><br /><br /><div id="cst">Total: <span >'+region.dollar_prefix+formatCurrency(total)+'</span></div><br /><br /><br /><div class="clear_both"></div><button id="checkout_button" onclick="jumpToHash(\'shippingdetails\')">Check out</button>';
    }else{
      var tt = parseFloat(freight)+total;
      html += '<br /><br /><br /><div class="update_mess" style="display: none">The cart has been updated.</div><br /><br /><div id="cst">Purchase: <span >$'+total.toFixed(2)+'</span></div>';
      html += '<div class="freight" id="fgt">freight: <span >$'+freight+'</span></div>';
      html += '<div class="freight" id="fgt2">Total: <span >$'+tt.toFixed(2)+'</span></div><br /><br />';
    }
    $('#cart').html(html+'</div><div class="clear_both">&nbsp;</div>');
  });
}

function change(ip){
  var qty = $('#qty'+ip).val();
  var total = $('#cst>span').text().substring(3);  /* remove first three characters (NZ$) */
	total = total.replace(',','');	/*convert total to a float */
  var o_su = $('#st'+ip).text();  //old subtotal
  var price = $('#cpp'+ip).text(); //price
  var n_st = parseFloat(qty*price);
  $('#st'+ip).html(n_st.toFixed(2));
  total = (total - parseFloat(o_su) + n_st);
  $('#cst>span').html(region.dollar_prefix+formatCurrency(total));
  // final total
  var freight = parseFloat($('#fgt>span').text().substring(1));
//  freight = freight;
  var tl = total+freight;
  $('#fgt2>span').html(formatCurrency(tl));
  //$.get(ewpath+'s/order/s',{action: 'change', modified_hidden:ip, modified_quan:qty}, function(d){
    $('#loading').slideDown();
  $.get(ewpath+'s/order/change',{id:ip, modified_quan:qty}, function(d){

    cart_detail();
  });
}

function remove(ip){
  var total = $('#cst>span').text();
  total = total.substring(3);			/* remove first three characters (NZ$) */
	total = total.replace(',','');	/*convert total to a float */
  var o_su = $('#st'+ip).text();
  total = (total - parseFloat(o_su));
  $('#cst>span').html(region.dollar_prefix+formatCurrency(total));
  $('#item'+ip).html('');
  // final total
  var freight = $('#fgt>span').text();
  freight = parseFloat(freight.substring(1));
  var tl = total+freight;
  $('#fgt2>span').html('$'+tl);
  //$.get(ewpath+'s/order/s',{action: 'delete', modified_hidden:ip}, function(d){
    $('#loading').slideDown();
  $.get(ewpath+'s/order/delete',{id:ip}, function(d){

    cart_detail();
  });
}

function checkout(){
    hide_all();
    $('#mycart').css("padding-top", "138px");
    $('#next_postal').show();
    $('#postal_form').show();

}
var currentPostcode = 0;
var postcodeXHR = false;
function find_postcode(){
  var postcode = $('#postcode').val();
  if(postcode == currentPostcode) {
    return false;
  }
  currentPostcode = postcode;
  $('#qmark').hide();
  if(!postcode) {
    $('#phint').hide();
    return false;
  }
  $('#qmark').html('<img src="images/indicator.gif" alt="find postcode"  width="15" height="15" />').show();
  if(postcodeXHR) postcodeXHR.abort();
  postcodeXHR = $.getJSON(ewpath+'s/order/get_postcode/', {postcode:$('#postcode').val()}, function(d){
        if(null==d || d=='[]' || d=='') {
          $('#phint').html('Unable to find that postcode, please confirm it.').show();
          $('#qmark').hide();
          return false;
        }
        var h = '(Select a correct postcode here)<br /><ul class="hint">';
          for(x in d) {
            h += '<li><div class="hc1">'+d[x].p+'</div><div class="hc2">'+d[x].c+'</div><div class="hc3">'+d[x].s+'</div></li>';
          }
          h+= '</ul>';
          $('#phint').html(h).show().find('ul.hint li').click(function () {
            $('#postcode').val($(this).find('.hc1').text());
            $('#city').val($(this).find('.hc2').text());
            $('#stateSELECT').val($(this).find('.hc3').text());
            $('#phint').hide();
          });
          $('#qmark').hide();
          postcodeXHR = false;
  });
}
var addda;
function checkAddress(){
    if(!check_postform())
        return false;
    var fields = $('#ptForm').serialize();
    $('#loading').slideDown();
    $.getJSON(ewpath+'s/order/save_postal/',fields,function(da){
        $('#loading').slideUp();
        if(da.charge)
        {
            fgt = da.charge;
						/* da.charge = fgt.toFixed(2); */
            addda = da;
            //credit_card_page(da);
            jumpToHash('confirm-order');
        }
        else
        {
            alert("Invalid postcode!");
        }
    });
}

function confirm_order () {
//function credit_card_page(){
  if (!addda) { jumpToHash('shippingdetails'); return; }
  changeProgressBar(2);
    hide_all();/*
    $('#credit_card').show(300);
    var htm='<br /><br />';
    //$.each(d, function(i, n) {
    //for(x in da){
      htm += '<div class="a1"><strong>Name:</strong></div><div class="a3">'+addda.name+'</div><br />';
       htm += '<div class="a1"><strong>Phone:</strong></div><div class="a3">'+addda.phone+'</div><br />';
      htm += '<div class="a1"><strong>Address:</strong></div><div class="a3">'+addda.company+'<br />'+addda.address1+'<br />'+addda.address2+'<br />'+addda.city+'<br />'+addda.state+'</div><br />';
    //}//});
    $('#ca_left').html(htm);
    var tail = '<br />If address is incorrect -  Return to <a href="#shippingdetails" rel="history">Change Postal</a><br /><br /><p>If everything is correct select your <a href="#payment-type">payment type</a></p>';
    $('#back_page').html(tail);
     view_cart(addda.charge);//view_cart(da.freight);
*/
    //credit_card_detail();

    $('#loading').slideDown();

    $('#confirmpage').find('.rfield').each(function () {
      if (!$(this).data('fieldname')) {
        $(this).data('fieldname',$(this).text());
      }
      $(this).text(addda[$(this).data('fieldname').toLowerCase()]);
    }).end().find('.addedRow').remove();

  $('#confirmfakerow').hide();

  $.getJSON(ewpath+'s/order/cart_detail', function(cart_info){
    $('#loading').slideUp();
    for(x in cart_info){
      $('#confirmfakerow').clone().addClass('addedRow').attr('id','')
        .insertAfter('#confirmfakerow').show().find('.frField')
        .each(function () {
          switch($(this).text()) {
            case 'name':
              $(this).text(cart_info[x].n);
              break;
            case 'quantity':
              $(this).text(parseInt(cart_info[x].q));
              break;
            case 'price':
              $(this).text(parseFloat(cart_info[x].p).toFixed(2));
              break;
            case 'subtotal':
              $(this).text((parseFloat(cart_info[x].p)*parseInt(cart_info[x].q)).toFixed(2)).addClass('addMe');
              break;
          }
        });
    }
    var addFunction = function () {
      var add = $('.addMe');
      var total = 0;
      for (i = 0; i < add.length; i++)
      {
        total += parseFloat($(add).eq(i).text());
      }

      $('#confirmTotal').text(region.dollar_prefix+formatCurrency(total));
      $('#confirmpage').show();
    }
    setTimeout(addFunction,100);
  });

}
function payment_type_select () {
    if (!$('#tosConfirm:checked').length) {
      alert('You must agree to our terms and conditions before proceeding');
      jumpToHash('confirm-order');
      return false;
    }
    $('#ca_left').html('');
    $('#back_page').html('');
    $('#cart').html('');

  hide_all();
    $('#paymentoption').show();
    /*
  $('#credit_card_detail').html('<table><tr><td>Direct Credit<br>'+
  '<p>Pay direct using internet banking. Simply transfer the total amount using the Ecobulb\'s® bank account number provided on the receipt and reference the order number. We will activate the order once payment has been confirmed.</p>'+
  '<a href="#payment-directcredit">Pay By Direct Credit</a>'+
  ''+
  '</td><td>Credit Card<br>'+
  '<p>Our secure online credit payment system accepts Visa, Mastercard, American Express and Diners. Your payment will be confirmed immediately via the DPS payment gateway.</p>'+
  '[Visa, Mastercard, American Express and Diners logos?]'+
  '<a href="#payment-creditcard">Pay By Credit Card</a>'+
  '</td></tr></table>'); */
}

function credit_card_detail(){
    var htm = '<p><div id="cc_form" name="cc_form">Enter your credit card '+
      'details to complete your order'+
      '</p><br /><br /><br />'+
      '<table><tbody><tr>'+
      '<th colspan="2">Credit Card Data</th></tr><tr><td align="right"> Card Holder Name '+
      '</td><td><input name="CardHolderName" value="" type="text" /> * </td>'+
      '</tr> <tr><td align="right"> Card Type </td><td>'+
      '<select name="CardType">'+
      '<option value="forgot" selected="selected">Choose Credit Card</option>'+
      '<option value="2">MasterCard</option>   <option value="1">Visa</option> '+
      '</select> * </td></tr><tr> <td align="right"> Card Number <br /> </td>'+
      '<td><input name="CardNumber" value="4111111111111111" type="text" /> *</td></tr> <tr> '+
      '<td align="right"> Expiration Date </td> <td>'+
      '<select name="ExprMonth" id="ExprMonth">  '+
      '<option value="forgot">--</option>  <option>01</option>  '+
      '<option>02</option>     <option>03</option>        <option>04</option> '+
      '<option>05</option>        <option>06</option>     '+
      '<option>07</option>        <option>08</option>        '+
      '<option>09</option>        <option>10</option>        <option>11</option>'+
      '<option>12</option> </select>        /       '+
      '<select name="ExprYear" id="ExprYear"> '+
      '<option value="forgot">--</option><option value="09">09</option> '+
      '<option value="10">10</option><option value="11">11</option> '+
      '<option value="12">12</option><option value="13">13</option>  '+
      '<option value="14">14</option><option value="15">15</option> '+
      '</select>        * </td>    </tr>    <tr>'+
      '<td align="right" valign="top"> CCV Code </td>      <td><p>       '+
      '<input name="cstCCV" value="" size="4" maxlength="4" type="text" /> '+
      '<br />        This is the 3 digit number<br />       '+
      'that appears on the reverse side of your <br />       '+
      'credit card (where your signature appears).<br />      '+
      'Amex cards only - the 4 digit number  on <br />        '+
      'the front of your card.<br />        <br />  '+
      '<img src="images/ccv.gif" alt="ccv" width="135" height="86" /><img src="images/paymark.png" alt="Paymark Certified" width="50" height="67" style="margin-left:125px" /></p></td>'+
      '</tr>  </tbody></table>'+
      '<input name="action" value="payCreditCard" type="hidden" />'+
      '<input name="Amount" id="Amount" value="" type="hidden" />'+
      '<button name="placeOrderButton" id="placeOrderButton" '+
      'onclick="javascript:document.getElementById(\'placeOrderButton\').disabled=true;'+
      'payCreditCard();">Submit</button><p></div></p>';
      hide_all();
      $('.update_mess').html('');
      // changed 20091002 by HostQuarters
      //$('#credit_card_detail').html(htm).show();
      $('#credit_card_detail').show();
      $('#credit_card_detail').html(htm);
}

function place_order2(w){
  hide_all();
  $('#after_payment').show();
  var receipt ='';
  $('#loading').slideDown();
  $.getJSON(ewpath+'s/order/cart_detail', function(cart_info){
    $('#loading').slideUp();
      if(null==cart_info){
        receipt = '<br />There is nothing in your Cart at this time.';
        return false;
      }else{
     /*   var total = 0;
        receipt = '<div class="r_bold"><div class="ct1">Product</div><div class="ct2" >Price</div><div class="ct3">Qty</div><div class="ct4">Subtotal</div></div><br />';
        for(x in cart_info){
          var st = 0;
          st += parseFloat(cart_info[x].p)*cart_info[x].q;
          receipt += '<br /><div class="eshopitem"><div class="ct1">'+cart_info[x].n+'</div><div class="ct2" >'+cart_info[x].p+'</div><div class="ct3">'+cart_info[x].q+'</div><div class="ct4">'+st+'</div></div><br />';
          total += st;
        }
        total += parseFloat(fgt);
        receipt += '<br /><div class="r_bold"><div class="ct1">&nbsp;</div><div class="ct2" ></div><div class="ct3">Freight</div><div class="ct4">$'+fgt+'</div></div><br />';
        receipt += '<br /><div class="r_bold"><div class="ct1">&nbsp;</div><div class="ct2" ></div><div class="ct3">Total</div><div class="ct4">$'+total.toFixed(2)+'</div></div><br /><br />';*/
      }

    $('#loading').slideDown();
    $.getJSON(ewpath+'s/order/pay_by_chequeordc/', {action: 'pay_by_chequeordc', type:w}, function(data){
      $('#loading').slideUp();
			$('#purchase_success').show();
      var url = ewpath+'s/order/invoice/'+data.receipt;
      //$('#after_payment').append('Please <a href="'+url+'" target="_blank">print invoice</a> for your records.<br /><iframe src="'+url+'" frameborder="0"></iframe>');
      $('#after_payment').append('<br /><br /><a href="'+url+'?print=y" target="_blank">Print Invoice</a><br /><iframe src="'+url+'" frameborder="0" style="width: 800px; height: 1200px; margin-left: -8px;"></iframe>');
      // grab the real invoice, don't create a fake one!!
        /* var mydate= new Date();
        var theyear=mydate.getFullYear();
        var themonth=mydate.getMonth()+1;
        var d = mydate.getDate();
        var s = d.toString();
        if(s.length<2)
          d = '0'+s;
        var today = d+'-'+themonth+'-'+theyear;
        var htm =' <b>Thank you for your Ecobulb® order !</b><br /><br /><a href="http://www.ecobulb.com.au">return to Ecobulb® home</a><br /><br /><br />'+'Please make payment to:<br />The Commonwealth Bank of Australia<br />06 2005 10648735<br />Reference: ['+invoice+'-'+today+']<br> *please reference order number when making automatic payment';
        $('#after_payment').html(htm);
        var sn = $('#fname').val()+' '+$('#lname').val();
        var a1 = $('#address1').val();
        var a2 = $('#shipaddress2').val();
        var sc = $('#city').val();
        var ss = ($('#state').val()).toLowerCase();
        ss = ss.substr(0, 1).toUpperCase() + ss.substr(1);
        var sy = $('#shipcountry').val();
        //var sp = $('#postcode').val();

        htm = '<br /><br /><br /><h3>Invoice</h3>'+invoice+'-'+today+'<br /><br />'+sn+'<br />'+a1+'<br />'+a2+'<br />'+sc+'<br />'+sy+'<br /> ------------------------------------------------------------------------<br />';
        $('#after_payment').append(htm); */
       // $('#after_payment').append(receipt);
      });
  });
}

function payCreditCard(){
  var fields = $('#cc_form :input').serialize();
  $('#loading').slideDown();
  //alert(ewpath+'s/order/payCreditCard/ \n '+fields);
  $.getJSON(ewpath+'s/order/payCreditCard/', fields, function(d){
      $('#loading').slideUp();
      if(parseInt(d.valid) > 0)
      {
        window.location.href = d.url;
      }
/*       var result = '<span style="color: red;">DECLINED </span></b>';

      var reason = '';
      if (f =='1' || f == 1) {
        result = '<span style="color: green;">'+'ACCEPTED'+' </span></b>';
        reason = '<b>Your transaction has been accepted!</b><br />'+
            'For your records, please print this page:';
      }else{
        reason = '<b>Sorry your transaction has been declined for the following reason:</b><br />';

       // result += '</b><br />Reason: <b>'+reason+'</b><br /><br />Please try again';
      }
      //alert(result);
      //alert(reason);


        switch(parseInt(f)) {
          case 1: reason += ''
          case 2: reason += 'Insufficient Funds'; break;
          case 3: reason += 'Card Expired'; break;
          case 4: reason += 'Card Declined'; break;
          case 5: reason += 'Server Error Occured'; break;
          case 6: reason += 'Communications Error'; break;
          case 7: reason += 'Unsupported Transaction Type'; break;
          case 8: reason += 'Bad or Malformed Request'; break;
          case 9: reason += 'Invalid Card Number'; break;
        }

            var r = d.result.split(',');
            var rr = r[r.length - 1].split('|');
            var tdate = new Date();
            tdate = tdate.getHours()+':'+
            (tdate.getMinutes() < 10 ? '0'+tdate.getMinutes() : tdate.getMinutes()) +' '+tdate.getDate()+'/'+(tdate.getMonth() + 1)+'/'+tdate.getFullYear();

            var htm = '<div class="receipt">'+
              reason+'<br /><br />'+
              'Receipt:<br /><br />'+
              'Ecobulb<br />xxxxxxxxxxxxxxxxxx<br />'+
              'Sydney, Australia<br />Merchant ID: 830557'+
              '<br />Date/Time: '+tdate+'<br />Order Reference: '+rr[1]+'<br />'+
              '<br />MerchTxnRef: '+r[1]+'<br />ReceiptNo: '+r[2]+'<br />'+
              'Purchase Amount: $'+rr[0]+'<br />Result:<b> '+result;

        if(f!='1'){
            document.getElementById('placeOrderButton').disabled=false;
            $('#ca_left, #ca_right, #back_page, #carry_shopping').hide();
            $('#credit_cart').append(htm);
        }else{
            $('#credit_card').html(htm);;
      $('#carry_shopping').hide();
            var url = '/engineware/s/order/invoice/'+d.invoice;
            $('#credit_card').append('<br /><br /><a href="'+url+'" target="_blank">Print Invoice</a><br /><iframe src="'+url+'" frameborder="0" style="width: 800px; height: 1200px; margin-left: -8px;"></iframe>');

        }

 */  });
}
function check_postform(){
    var sfn=$('#fname').val();
    var sln=$('#lname').val();
    var sm=$('#email').val();
    var scy=$('#company').val();
    var sp=$('#phone').val();
    var sa=$('#address1').val();
    var sct=$('#city').val();
    var sst=$('#stateSELECT').val();
    //alert('state:'+sst);
    var spc=$('#postcode').val();
    if(sfn==''||sln==''){
        alert('Please enter your first and last name');
        return false;
    }
    /* if(scy==''||scy==null){
        alert('Company is required.');
        return false;
    } */
   if(sp==''||sp==null){
        alert('Phone number is required');
        return false;
    }
    if(!isInteger(sp)){
      // ignore .. who cares
       //alert('Please fill number only in phone field.');
       //return false;
    }
    if(sa==''||sa==null){
        alert('Address is required.');
        return false;
    }
    if(sct==''||sct==null){
        alert('City is required.');
        return false;
    }
    if(sst==''||sst==null){
        alert('State is required');
        return false;
    }
    if(spc==''||spc==null){
        alert('Postcode is required');
        return false;
    }
    if(sm=='' ||sm==null){alert('Email address cannot be blank.');return false;}
    if(!echeck(sm)){alert('Please check your email address, it doesn\'t appear valid'); return false;}
    return true;
}
function isInteger(s){
    // what is wrong with return (parseInt(s) == s);
    var i;
    for (i = 0; i < s.length; i++){
        var c = s.charAt(i);
        if (((c < "0") || (c > "9"))&&(c!=" ")) return false;
    }
    return true;
}
function echeck(str) {
    var at="@"
    var dot="."
    var lat=str.indexOf(at)
    var lstr=str.length
    var ldot=str.indexOf(dot)
    if (str.indexOf(at)==-1){
       return false
    }
    if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
       return false;
    }
    if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
        return false;
    }
     if (str.indexOf(at,(lat+1))!=-1){
        return false;
     }
     if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
        return false;
     }
     if (str.indexOf(dot,(lat+2))==-1){
        return false;
     }
     if (str.indexOf(" ")!=-1){
        return false;
     }
     return true;
}




function getScrollY() {
  var scrOfX = 0, scrOfY = 0;
  if( typeof( window.pageYOffset ) == 'number' ) {
    //Netscape compliant
    scrOfY = window.pageYOffset;
    scrOfX = window.pageXOffset;
  } else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
    //DOM compliant
    scrOfY = document.body.scrollTop;
    scrOfX = document.body.scrollLeft;
  } else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
    //IE6 standards compliant mode
    scrOfY = document.documentElement.scrollTop;
    scrOfX = document.documentElement.scrollLeft;
  }
  //return [ scrOfX, scrOfY ];
  return scrOfY;
}
function getWindowHeight() {
  var myWidth = 0, myHeight = 0;
  if( typeof( window.innerWidth ) == 'number' ) {
    //Non-IE
    myWidth = window.innerWidth;
    myHeight = window.innerHeight;
  } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
    //IE 6+ in 'standards compliant mode'
    myWidth = document.documentElement.clientWidth;
    myHeight = document.documentElement.clientHeight;
  } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
    //IE 4 compatible
    myWidth = document.body.clientWidth;
    myHeight = document.body.clientHeight;
  }
  return myHeight;
//  window.alert( 'Width = ' + myWidth );
//  window.alert( 'Height = ' + myHeight );
}


/*
 * jQuery history plugin
 *
 * Copyright (c) 2006 Taku Sano (Mikage Sawatari)
 * Licensed under the MIT License:
 *   http://www.opensource.org/licenses/mit-license.php
 *
 * Modified by Lincoln Cooper to add Safari support and only call the callback once during initialization
 * for msie when no initial hash supplied.
 */


jQuery.extend({
  historyCurrentHash: undefined,

  historyCallback: undefined,

  historyInit: function(callback){
    jQuery.historyCallback = callback;
    var current_hash = location.hash;

    jQuery.historyCurrentHash = current_hash;
    if ((jQuery.browser.msie) && (jQuery.browser.version < 8)) {
      // To stop the callback firing twice during initilization if no hash present
      if (jQuery.historyCurrentHash == '') {
      jQuery.historyCurrentHash = '#';
    }

      // add hidden iframe for IE
      $("body").prepend('<iframe id="jQuery_history" style="display: none;"></iframe>');
      var ihistory = $("#jQuery_history")[0];
      var iframe = ihistory.contentWindow.document;
      iframe.open();
      iframe.close();
      iframe.location.hash = current_hash;
    }
    else if ($.browser.safari) {
      // etablish back/forward stacks
      jQuery.historyBackStack = [];
      jQuery.historyBackStack.length = history.length;
      jQuery.historyForwardStack = [];

      jQuery.isFirst = true;
    }
    jQuery.historyCallback(current_hash.replace(/^#/, ''));
    setInterval(jQuery.historyCheck, 100);
  },

  historyAddHistory: function(hash) {
    // This makes the looping function do something
    jQuery.historyBackStack.push(hash);

    jQuery.historyForwardStack.length = 0; // clear forwardStack (true click occured)
    this.isFirst = true;
  },

  historyCheck: function(){
    if ((jQuery.browser.msie) && (jQuery.browser.version < 8)) {
      // On IE, check for location.hash of iframe
      var ihistory = $("#jQuery_history")[0];
      var iframe = ihistory.contentDocument || ihistory.contentWindow.document;
      var current_hash = iframe.location.hash;
      if(current_hash != jQuery.historyCurrentHash) {

        location.hash = current_hash;
        jQuery.historyCurrentHash = current_hash;
        jQuery.historyCallback(current_hash.replace(/^#/, ''));

      }
    } else if ($.browser.safari) {
      if (!jQuery.dontCheck) {
        var historyDelta = history.length - jQuery.historyBackStack.length;

        if (historyDelta) { // back or forward button has been pushed
          jQuery.isFirst = false;
          if (historyDelta < 0) { // back button has been pushed
            // move items to forward stack
            for (var i = 0; i < Math.abs(historyDelta); i++) jQuery.historyForwardStack.unshift(jQuery.historyBackStack.pop());
          } else { // forward button has been pushed
            // move items to back stack
            for (var i = 0; i < historyDelta; i++) jQuery.historyBackStack.push(jQuery.historyForwardStack.shift());
          }
          var cachedHash = jQuery.historyBackStack[jQuery.historyBackStack.length - 1];
          if (cachedHash != undefined) {
            jQuery.historyCurrentHash = location.hash;
            jQuery.historyCallback(cachedHash);
          }
        } else if (jQuery.historyBackStack[jQuery.historyBackStack.length - 1] == undefined && !jQuery.isFirst) {
          // back button has been pushed to beginning and URL already pointed to hash (e.g. a bookmark)
          // document.URL doesn't change in Safari
          if (document.URL.indexOf('#') >= 0) {
            jQuery.historyCallback(document.URL.split('#')[1]);
          } else {
            var current_hash = location.hash;
            jQuery.historyCallback('');
          }
          jQuery.isFirst = true;
        }
      }
    } else {
      // otherwise, check for location.hash
      var current_hash = location.hash;
      if(current_hash != jQuery.historyCurrentHash) {
        jQuery.historyCurrentHash = current_hash;
        jQuery.historyCallback(current_hash.replace(/^#/, ''));
      }
    }
  },
  historyLoad: function(hash){
    var newhash;

    if (jQuery.browser.safari) {
      newhash = hash;
    }
    else {
      newhash = '#' + hash;
      location.hash = newhash;
    }
    jQuery.historyCurrentHash = newhash;

    if ((jQuery.browser.msie) && (jQuery.browser.version < 8)) {
      var ihistory = $("#jQuery_history")[0];
      var iframe = ihistory.contentWindow.document;
      iframe.open();
      iframe.close();
      iframe.location.hash = newhash;
      jQuery.historyCallback(hash);
    }
    else if (jQuery.browser.safari) {
      jQuery.dontCheck = true;
      // Manually keep track of the history values for Safari
      this.historyAddHistory(hash);

      // Wait a while before allowing checking so that Safari has time to update the "history" object
      // correctly (otherwise the check loop would detect a false change in hash).
      var fn = function() {jQuery.dontCheck = false;};
      window.setTimeout(fn, 200);
      jQuery.historyCallback(hash);
      // N.B. "location.hash=" must be the last line of code for Safari as execution stops afterwards.
      //      By explicitly using the "location.hash" command (instead of using a variable set to "location.hash") the
      //      URL in the browser and the "history" object are both updated correctly.
      location.hash = newhash;
    }
    else {
      jQuery.historyCallback(hash);
    }
  }
});


function changeProgressBar(step) {
  $('#progress')
      .removeClass('step1')
      .removeClass('step2')
      .removeClass('step3')
      .removeClass('step4')
  if (parseInt(step)) {
    $('#progress')
      .addClass('step'+step.toString()).show();
  }else{
    $('#progress')
      .hide();
  }
}

function formatCurrency(num) {
	num = num.toString().replace(/\$|\,/g,'');
	if(isNaN(num))
	num = "0";
	sign = (num == (num = Math.abs(num)));
	num = Math.floor(num*100+0.50000000001);
	cents = num%100;
	num = Math.floor(num/100).toString();
	if(cents<10)
	cents = "0" + cents;
	for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
	num = num.substring(0,num.length-(4*i+3))+','+
	num.substring(num.length-(4*i+3));
	return (((sign)?'':'-') + '$' + num + '.' + cents);
}
