// Cookie utility functions from
// http://www.quirksmode.org/js/cookies.html
function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}
// end cookie functions

// Newsletter popup functions
var popup = new Object();
popup.shown = false;
popup.lastY = 0;

function popupShownCount(){
  var x = readCookie('numPopups');
  if (!x){
    createCookie('numPopups',0,7);
    x = 1;
  }
  return Number(x);
}

function popupLastShown(interval){
  var lastshown = readCookie('popupLastShown');
  if (!lastshown) {
    var d = new Date();
    lastshown = d.getTime();
    createCookie('popupLastShown',lastshown-interval,1); // so pops right away
  }
  return (Number(lastshown));
}

function trackerPopup(max){
  if (document.URL.search(/search.store.yahoo.net/) == -1){
    $().bind('mousemove',
    function(e){
      if (!popup.shown){
	var pops = popupShownCount();
	if ( (max > pops) && (e.pageY < popup.lastY) && (e.pageY < 75) ) {
	  tb_show("Join Our Newsletter!","http://mail.big-fitness.com/newsletter_forms/newsletter2.html?KeepThis=true&TB_iframe=true&height=330&width=300");
	  popup.shown = true;
	  createCookie('numPopups',pops+1,7); // increment counter
	}
      }
      popup.lastY = e.pageY;
    });
  }
}
// end newsletter popup functions


function goURL(url){
  window.location = url;
}

function checkFormTextAndEmail(formname){
  var thisform = document['forms'][formname];
  var res = true;
  for (i in thisform){
    var e = thisform[i];
    if (e && (e.type === 'text' ||
	      e.type === 'textarea' || e.type === 'password')){
      if (e.name.search(/email/i) != -1){
	res = e.value.search(/.+@.+/) == -1 ? false : true;
      }
      else if (e.value.search(/^\s*$/) != -1){
	res = false;
	}
      }
  }
  return res;
}

function checkTabForms(formname,message){
  if (checkFormTextAndEmail(formname,message)){
    if (formname == 'post'){
      open_win();
    }
    else if (formname == 'post1'){
      open_win1();
    }
  }
  else{
    alert(message);
  }
}


function scrollContentDiv(divId){
  switch (divId){
  case "#cont7":
    $(divId).animate(
      {scrollTop: $('#fq_content').outerHeight()});
    break;
  case "#cont8":
    $(divId).animate(
      {scrollTop: $("#reviews_content").outerHeight()});
    break;
  }
}

function highlightRentalTab(){
  $("a:contains('Rental Information')").parent().parent().parent().removeClass().addClass('redTab');
}

function setPhoneByTime(nowtime){
  var hour = nowtime.getUTCHours();
  var phoneDiv = $('#tnText > div');
  if (hour >= 0 && hour < 14){
    phoneDiv.text('Call us: 401-885-5200');
  }
  else{
    phoneDiv.css('color','#990000');
    phoneDiv.text('Call to order: 1-800-731-0098');
  }
}

function showPopup(){
  try{
    if (brandname == 'Star Trac'){
      $('body').append('<div id="stcoupon"><img src="http://files.bigfitness.com/stpopup-noe.png"></div>');
      $('#stcoupon').bind('click',
                       function(){$('#stcoupon').hide();});
      $('#stcoupon').css({width: '350px', height: '330px',visibility: 'visible'}).hide().show('fast');
    }
  }
  catch(e){
    // do nothing
    }
  }


function preloadImages(){
  var imagelist = ['http://files.bigfitness.com/layaway/laybutton-normal.gif',
	   'http://files.bigfitness.com/layaway/laybutton-pressed.gif',
		   'http://files.bigfitness.com/ezpay/ez-normal.png',
		   'http://files.bigfitness.com/ezpay/ez-pressed.png'];
  for (i in imagelist){
    $('<img>').attr('src',imagelist[i]);
  }
}
pp = new Object();
shippingNotIncluded = ['WATERROWS1','WATERROWCH','WATERROWER','WATERROWM1LO','WATERROWM1HI','WATERROWCLUBM','WATERROWCL',
		       'newitem1','newitem1139516725','newitem1139517348','newitem1139517587','PrecorC956iW','tc5300','U2165D'];

function showAssemblyButton(amt){
  if (amt > 299){
    var ihimg = document.createElement('img');
    ihimg.src = 'http://files.bigfitness.com/inhome-t.png';
    ihimg.style.cssText = 'margin-top: 5px;';
    ihimg.onclick = showAssembly;
    ihimg.width = 110;
    ihimg.height = 52;
    var ihDiv = document.createElement('div');
    $('#itemDiv div:eq(0)').append(ihimg);
  }
}

function showAssembly(){
  $('#assembly').css({visibility: 'visible',
                      width: '600px',
		      height: '500px'}).hide().show('fast');
}

function showUnderpriceBox(){
  if (nobox == 'NO'){
//    var buttonDiv;
//    if (ezpay == 'NO'){
//      buttonDiv = '<div id="layawayDiv">';
//      buttonDiv += '<img class="laybutton" src="http://files.bigfitness.com/layaway/laybutton-normal.gif" onclick="showLayaway()" alt="Layaway Now">';
//      buttonDiv += '<BR><strong>Pay Over Time - No Interest</strong><BR>';
//      buttonDiv += '<a href="layaway.html"><small>Click here for details.</small></a></div>';
//    }
//    else {
//      buttonDiv = '<div id="ezPayDiv">';
//      buttonDiv += '<img class="ezbutton" src="http://files.bigfitness.com/ezpay/ez-normal.png" onclick="showEZPay()" alt="Layaway Now">';
//      buttonDiv += '<BR><strong>Three Easy Payments!</strong><BR>';
//      buttonDiv += '<small>Click button for details.</small></div>';
//    }
//    $('#under_order_right').append(buttonDiv);
    MakeCreditLink();
    $('#underprice_box').css('visibility','visible').show();
  }
}

// BIG LAYAWAY FUNCTIONS
function layButtonUp(e){
  $('.laybutton').attr('src','http://files.bigfitness.com/layaway/laybutton-normal.gif');
}
function layButtonDown(e){
  $('.laybutton').attr('src','http://files.bigfitness.com/layaway/laybutton-pressed.gif');
}
function showLayaway(e){
  var laypayments = $('input[name="pricetxt"]').val().slice(1);
  laypayments = formatPrice(parseFloat(laypayments)/4);
  $("#laypayments").append(laypayments);
  $("#layaway")
    .hide()
    .css({visibility: "visible",
	  width: "550px",
	  height: "450px"})
    .show('slow');
  }
// EZPAY FUNCTIONS
function ezButtonUp(e){
  $('.ezbutton').attr('src','http://files.bigfitness.com/ezpay/ez-normal.png');
}
function ezButtonDown(e){
  $('.ezbutton').attr('src','http://files.bigfitness.com/ezpay/ez-pressed.png');
}
function showEZPay(e){
  var laypayments = $('input[name="pricetxt"]').val().slice(1);
  var firstPayment = formatPrice(parseFloat(laypayments)*.4);
  var otherPayments = formatPrice(parseFloat(laypayments)*.3);
  $("#ezpay_first").append(firstPayment);
  $("#ezpay_rest").append(otherPayments);
  $("#ezpay")
    .hide()
    .css({visibility: "visible",
	  width: "550px",
	  height: "450px"})
    .show('slow');
  }
// END ELAY / EZPAY FUNCTIONS

function formatPrice(price){
  var strPrice = "$" + (Math.round(price*100)/100).toFixed(2);
  return strPrice;
  }

function binarySearch(list,key){
  var i = 0;
  var j = list.length - 1;
  var m = -1;
  while( i <= j ){
    m = Math.floor((i + j) / 2);
    if( key < list[m] ){ // left half
      j = m - 1;
    } else if( list[m] < key ){  // right half
      i = m + 1;
    } else {  // found
      return m;
    }
  }
  return -1;  // not present
}

var callButtonURL = "http://site.bigfitness.com/i/callbutton-big.png";
function changeOrderToCall(){
  $(".bt:first > input").attr("src",callButtonURL);
  }
function disableOrderButton(){
  var callButton = document.createElement("img");
  $(callButton).attr({src: callButtonURL,
                      width: 168,
                      height: 35});
  $(".bt:first a").replaceWith(callButton);
  }

function setAvailability(){
  var availSpan = $(".avl:first > span");
  var origAvailText = availSpan.text();
  var availText = origAvailText;
  var bo = false;
  if (availText.search(/discontinued/i) != -1){
    bo = true; // do not change availText
  }
  else if (availText.search(/out|call|back|^no$/i) != -1){
    availText = "Call for availability.";
    //changeOrderToCall();
    disableOrderButton();
    bo = true;
  }
  else if (brandname.search(/troy/i) != -1 && !bo){
    availText = "Ships in 5-7 business days.";
  }
  else if (brandname.search(/cap/i) != -1 && !bo){
    availText = "Ships in 1-5 business days.";
  }
  else if (brandname.search(/xvest/i) != -1 && !bo){
    availText = "Ships in 3 weeks.";
  }
  else if (brandname === 'TKO' && !bo){
    availText = "Ships in 3-5 business days.";
  }
  else if (usedcardio === 'YES' && !bo){ // global variable set in template
    availText = "Ships in 1-2 weeks.";
  }
  else if (brandname == 'Star Trac' && !bo){
    availText = "Ships in 4 -7 business days.";
  }
  if (availText !== origAvailText){
    availSpan.text(availText);
  }
  // Remove "shipping included" badge if in list
  if ($.inArray(SKU,shippingNotIncluded) == -1 && noShipIncluded == 'NO'){
      $("#shippingIncluded > img").attr("src","http://site.bigfitness.com/i/shipping-included.gif");
  }
}

function promo(){}

function _createTipLink(o,link){
  var l = document.createElement('a');
  l.href = o.href;
  l.id = o.id;
  //l.title = o.title;
  l.className = 'jTip';
  return(l);
  }

function _makeTip(id,text,header){
  $('#'+id).hover(function(){JT_show(text,this.id,header);},function(){$('#JT').remove();});
  }

function formatOptions(){
  var infoLink = "javascript:popper('aboutus.html#Shipping',1000,600,1)";
  var infoNote = "<P><strong>Click link for more info.</strong></P>";
 $("input[@name$='Delivery Options'] + span").each(
 function(i){
  var option = $(this).text();
  var l;
  var text;
  var header;
  if (option.search(/Standard \(/) != -1){
    l = _createTipLink({id: "STANDARD",
                      href: infoLink});
    text = "<P>Truck will stop at curbside.<BR>Customer is responsible for removing merchandise from the truck and moving it indoors.</P>" + infoNote;
    header = "Standard Common Carrier";
    }
  else if (option.search(/Lift Gate/) != -1){
    l = _createTipLink({id: "LIFTGATE",
                        href: infoLink});
    text = "<P>Truck will come equipped with hydraulic lift gate that will lower merchandise to street level.<BR>Customer is responsible for moving the merchandise indoors.</P>" + infoNote;
    header = "Standard Common Carrier with Lift Gate";
    }
  else if (option.search(/Threshold/) != -1){
    l = _createTipLink({id: "THRESHOLD",
                       href: infoLink});
    text = "<P>Service to residential driveway, garage, inside front porch or door using a lift-gate equipped truck, pallet jack or hand truck.</P>"
           + infoNote;
    header = "Threshold Delivery";
    }
  else if (option.search(/Deluxe 2-Person/) != -1){
    l = _createTipLink({id: "DELUXE",
                       href: infoLink});
    text = "<P>Service to room of choice (max two flights of stairs), including de-skidding, placement and cardboard box/debris removal.&nbsp;&nbsp;Does not include equipment setup.</P>" + infoNote;
    header = "Deluxe 2-Person Inside Delivery";
    }
  else if (option.search(/White Glove/) != -1){
    l = _createTipLink({id: "WHITEGLOVE",
                       href: "#"});
    text = "<P>Full delivery, assembly and cleanup for your new Landice!</P>";
    header = "White Glove Delivery & Assembly";
    }
   else { // No match
     return false;
   }
  $(this).wrap(l);
  _makeTip(l.id,text,header);
  });

  $("input[@name$='Fast Shipping'] + span").each(
 function(i){
  var option = $(this).text();
  var l;
  var text;
  var header;
  if (option.search(/Standard Ground/) != -1){
    l = _createTipLink({id: "STANDARDGROUND",
                      href: infoLink});
    text = "<P>Standard UPS Ground.<BR>Delivery in 2-6 business days.</P>";
    header = "Standard Ground";
    $(this).wrap(l);
    _makeTip(l.id,text,header);
    }
  else if (option.search(/2nd Day/) != -1){
    l = _createTipLink({id: "SECONDDAY",
                      href: infoLink});
    text = "<P>Delivery by end of second business day.<BR>Delivery charge assessed per item. Other items in your order will ship via standard shipping.</P><P><strong>Please allow one business day for us to process your order.</strong></P>";
    header = "2nd Day Air";
    $(this).wrap(l);
    _makeTip(l.id,text,header);
    }
  else if (option.search(/Next Day/) != -1){
    l = _createTipLink({id: "NEXTDAY",
                      href: infoLink});
    text = "<P>Delivery by 4:30 PM the next business day (by 3:30 PM many metro areas).<BR>Delivery charge assessed per item. Other items in your order will ship via standard shipping.</P><P><strong>Please allow one business day for us to process your order.</strong></P>";
    header = "Next Day Air Saver";
    $(this).wrap(l);
    _makeTip(l.id,text,header);
    }
  });
}

function MakeCanadaTip(){
  var text = '<P><strong>We now ship to the following provinces in Canada:</strong><BR>';
  text += '<small>Alberta, BC, Manitoba, New Brunswick, Nova Scotia, Ontario, Quebec, Saskatchewan</small><BR><BR>';
  text += 'CANADIAN ORDERS WILL BE CHARGED TAXES AND SHIPPING.<BR><BR>';
  text += '<small>Items with a lead-time (see <strong>Availability</strong> above) must be shipped to our warehouse first before they can be shipped to Canada.&nbsp;&nbsp;';
  text += 'Please allow the indicated lead-time, 3-5 business days shipping time to our warehouse, plus one day for handling <em>before</em> your order will ship.</small>';
  var header = 'CANADIAN SHIPPING DETAILS';
  $('#cainfo').hover(function(){JT_show(text,this.id,header);},function(){$('#JT').remove();});
}

function MakeShipTip(){
  var text = '<P>Shipping included except to Alaska, Hawaii, and Canada.</P>';
  var header = 'Shipping Included Details';
  $('#shippingIncluded').hover(function(){JT_show(text,this.id,header);},function(){$('#JT').remove();});
}


function MakeCreditLink(){

  var noFinList = new Array('GC25','GC50','GC75','GC100','GC150','GC200','GC250','GC350','GC400','GC450','GC500','GC750','GC1000');
  var numPrice = Number(sprice);
  var financeType;

  if (numPrice >= 1000){
    financeType = "twelve";
    }
  else if (numPrice >= 100){
    financeType = "three";
    }
  else{
    financeType = "none";
    }

  for (i in noFinList){
    if (noFinList[i] == SKU){
      financeType = "none";
      break;
    }
  }
  // Make payments string
  var numpayments = (Math.round((numPrice*0.03)*100))/100;
  var payments = formatPrice(numpayments);
  var paymentsText = 'as '+payments+' a month.';

  var instantSpan =  $('<span/>').css({'color': 'blue', 'font-weight': 'bold' });
  var creditlink = $('<a/>').attr('href','creditapp.html').css({'font-weight': 'bold', 'color': 'green'});
  $('#FIN').append(instantSpan.text('INSTANT FINANCING AVAILABLE'));
  $('#FIN').append('<BR>');
  $('#FIN').append(creditlink.text('Call 800-383-2008 For Details!'));
}

function popper(popurl,w,h,flag){
  if (arguments.length != 4) flag=0;
  if (w == 800) w = 1000;
  var winpops=window.open(popurl,"","width="+w+",height="+h+",status=1,scrollbars=1,resizable=1,menubar="+flag+",toolbar="+flag+",location="+flag);
}

function SBPForm(){
  prodname = escape(document.title);
  var formURL = "http://files.bigfitness.com/forms/sbp.php?prodname="+prodname+"&sku="+SKU+"&sprice="+sprice+"&pid="+pid;
  popper(formURL,640,500,1);
}

function intlshipping(){
  var url = "http://files.bigfitness.com/forms/canada-shippingform.php?sku=" + SKU + "&prodname=" + document.title;
  popper(url,600,600,1);
}

function showCoupon(){
  if (nocoupon ==='NO'){
    $('#couponDiv').slideDown();
  }
}

function goDirectlyToCart(){

  var cartUrl = 'http://order.store.yahoo.net/cgi-bin/wg-order?bigfit';
  if (window.location.search.search('scripty=GOCART') != -1){
    window.location.href = cartUrl;
  }
}

$().ready(
  function(){
    formatOptions();
//    $('#under_order_right a[href="layaway.html"]')
//      .removeAttr('href')
//      .bind('click',showLayaway);
//    $('.laybutton')
//      .bind('mouseup',layButtonUp)
//      .bind('mousedown',layButtonDown)
//      .bind('mouseout',layButtonUp);
//    $('.ezbutton')
//      .bind('mouseup',ezButtonUp)
//      .bind('mousedown',ezButtonDown)
//      .bind('mouseout',ezButtonUp);
    preloadImages();
    setPhoneByTime(new Date());
    highlightRentalTab();
    MakeCanadaTip();
    MakeShipTip();
    goDirectlyToCart();
//    showCoupon();
//    trackerPopup(1);
  });
