var pendingRequest = false;
var async = null;
var slide = 1;
var maxSlides = 8;
var carousel = null;

function setPending(target) {
  pendingRequest = true;
	var div = document.getElementById(target);
 	div.innerHTML = "";
 	//if (div != null) div.innerHTML = "<br/><img src='/images/progress.gif' alt='Please Wait...' align='center' /> Loading ... (<a href='javascript:stopRequest()'><img src='/images/icons/link_break.png' alt='x' /></a>)<br/><br/><br/>";
}

var handleSuccessRequest = function(o) {
  pendingRequest = false;
  arguments = o.argument.split(":")
  div = document.getElementById(arguments[0]); // alert("arg: " + arguments[0]);
	if (o.responseText !== undefined) {
		div.innerHTML = o.responseText;
		if (arguments.length > 1) {
		  div = document.getElementById(arguments[1]);
		  if ((div != null) && (div.disabled == false)) div.focus();
		}
		if (arguments.length > 2) {
		  functionCall = eval(arguments[2]);
		  functionCall();
		}
	} else {
	  div.innerHTML = "<br/>Processing Failed.  Please Reload and Try Again.<br/><br/><br/>";
	}
};

var handleFailureRequest = function(o) {
  pendingRequest = false;
  arguments = o.argument.split(":")
	div = document.getElementById(arguments[0]);
	div.innerHTML = "<br/>Processing Failed.  Please Reload and Try Again.<br/><br/><br/>";
};

var handleAbortRequest = function(o) {
  pendingRequest = false;
  arguments = o.argument.split(":")
	div = document.getElementById(arguments[0]);
	div.innerHTML = "<br/>Transaction aborted.<br/><br/><br/>";
};

var callbackRequest =
{
  success:handleSuccessRequest,
  upload:handleSuccessRequest,
  failure:handleFailureRequest,
  abort:handleAbortRequest,
  timeout: 2000000
};

function stopRequest() {
  result = YAHOO.util.Connect.abort(async, callbackRequest);
}

function coreGetLoop(target, url, focus, functionCall) {
  if (!pendingRequest) {
		setPending(target);
		callbackRequest['argument'] = target + ':' + focus + ':' + functionCall;
	  async = YAHOO.util.Connect.asyncRequest('GET', url, callbackRequest);
	}
}

function corePostLoop(target, url, targetform, multipart, focus, functionCall) {
  if (!pendingRequest) {
		setPending(target);
		callbackRequest['argument'] = target + ':' + focus + ':' + functionCall;
		YAHOO.util.Connect.setForm(targetform, multipart);
	  async = YAHOO.util.Connect.asyncRequest('POST', url, callbackRequest);
	}
}

function refreshPayment() {
  //alert('Submission Complete');
  var div = document.getElementById('cart');
  div.innerHTML = "";
  if (document.getElementById('result').innerHTML.indexOf("Success") >= 0) {
    // alert('Payment Processed');
    div = document.getElementById('cartID');
    var cartID = 0;
    if (div != null) cartID = div.value;
	  pageTracker._trackPageview("/payment.php5");
	  pageTracker2._trackPageview("/payment.php5");
    location.href = '/thankyou.php5?cartID=' + cartID;
  } else {
	  var count = document.getElementById('paymentform').elements.length;
	  for (i=0; i<count; i++) {
	    var element = document.getElementById('paymentform').elements[i]; 
	    element.disabled=false;
	  }
	}
}

function notvalid(str) {
  value = document.getElementById(str).value;
  notvalidresult = ((value == null) || (value == "") || (value.charAt(0) == ' '));
  if (notvalidresult) document.getElementById(str).focus();
  return notvalidresult;
}

function updateTotal(total) {
	var giftWrap = document.getElementById('giftWrapping');
	var giftWrapFee = document.getElementById('giftWrapFee');
	var div = document.getElementById('state');
	var divSalesTax = document.getElementById('salestax');
	var divTotal = document.getElementById('total');
	var st = div.options[div.selectedIndex].value;
	if (st.toUpperCase() == 'NJ') {
	  taxes = total * 0.07;
	  total = total + taxes;
	  divSalesTax.innerHTML = "$" + taxes.toFixed(2);
	} else {
	  divSalesTax.innerHTML = "$0.00";
	}
	if(giftWrap.checked == true) {
	  total = total + 5.00;
	  giftWrapFee.innerHTML = "$5.00";
    show('giftForm');
	} else {
	  giftWrapFee.innerHTML = "$0.00";
    hide('giftForm');
	}
  divTotal.innerHTML = "$" + (total + 12.95).toFixed(2);
}

function processPayment() {
  if (notvalid("firstName")) {
    alert('Please provide your First Name');
  } else if (notvalid("lastName")) {
    alert('Please provide your Last Name');
  } else if (notvalid("ccn")) {
    alert('Please provide a valid Credit Card');
  } else if (notvalid("cvv")) {
    alert('Please provide a valid CVV2 Number');
  } else if (notvalid("expMonth") || notvalid("expYear")) {
    alert('Please provide a valid Expiration Date');
  } else if (notvalid("address1")) {
    alert('Please provide a valid Address');
  } else if (notvalid("city")) {
    alert('Please provide a valid City');
  } else if (notvalid("state")) {
    alert('Please provide a valid State');
  } else if (notvalid("zipCode")) {
    alert('Please provide a valid Zip Code');
  } else if (notvalid("phone")) {
    alert('Please provide a valid Phone Number');
  } else if (notvalid("email")) {
    alert('Please provide a valid Email Address');
  } else {
	  var div = document.getElementById('cart');
	  div.innerHTML = "<center><br/><br/><h3>Processing Payment - Please Wait</h3><br/><br/></center>";
    corePostLoop('result', '/payment.php5', document.getElementById('paymentform'), false, 'firstName', 'refreshPayment');
	  var count = document.getElementById('paymentform').elements.length;
	  for (i=0; i<count; i++) {
	    var element = document.getElementById('paymentform').elements[i]; 
	    element.disabled=true;
	  }
  }
}

function refreshPage() {
  window.location.href=window.location.href;
}

function removeOptionList(productID) {
  coreGetLoop('result', '/intranet/includes/UpdateOptionList.php5?mode=delete&id=' + productID, 'name', 'refreshPage');
}

function removeOptionList(productID) {
  coreGetLoop('result', '/intranet/includes/UpdateOptionList.php5?mode=delete&id=' + productID, 'name', 'refreshPage');
}

function removeItem(cartItemID) {
  coreGetLoop('result', '/intranet/includes/UpdateCart.php5?mode=delete&id=' + cartItemID, 'container', 'refreshPage');
}

function createOptionList() {
  corePostLoop('result', '/intranet/includes/UpdateOptionList.php5', document.getElementById('createform'), false, 'name', 'refreshPage');
}

function search() {
  var term = document.getElementById('term').value;
  coreGetLoop('searcharea', '/searchresults.php5?term=' + term, 'term', 'noop');
  pageTracker._trackPageview("/searchresults.php5?term=" + term);
  pageTracker2._trackPageview("/searchresults.php5?term=" + term);
}

function noop() {}

function displayEmail() {
  hide("imagearea");
  show("title_undeline");
  show("theform");
}

function cancelEmail() {
  show("imagearea");
  hide("title_undeline");
  hide("theform");
}

function sendtofriend(productID) {
  corePostLoop('result', '/sendmail.php5?id=' + productID, document.getElementById('formulario'), false, 'ea', 'refreshPage');
  pageTracker._trackPageview("/sendmail.php5?id=" + productID);
  pageTracker2._trackPageview("/sendmail.php5?id=" + productID);
  hide("title_undeline");
  hide("theform");
  alert("Your email has been saved and will be sent shortly.");
}

function sendform() {
  if (notvalid("companyName")) {
    alert('Please provide your Company Name');
  } else if (notvalid("contactPerson")) {
    alert('Please provide your Company Contact Person');
  } else if (notvalid("companyAddress")) {
    alert('Please provide a valid Address');
  } else if (notvalid("city")) {
    alert('Please provide a valid City');
  } else if (notvalid("state")) {
    alert('Please provide a valid State');
  } else if (notvalid("zipCode")) {
    alert('Please provide a valid Zip Code');
  } else if (notvalid("phone")) {
    alert('Please provide a valid Phone Number');
  } else if (notvalid("email")) {
    alert('Please provide a valid Email Address');
  } else if (notvalid("taxID")) {
    alert('Please provide a valid Tax ID');
  } else if (notvalid("url")) {
    alert('Please provide a valid Website URL');
  } else {
    corePostLoop('theform', '/sendform.php5', document.getElementById('formulario'), false, 'theform', 'noop');
    pageTracker._trackPageview("/sendform.php5");
    pageTracker2._trackPageview("/sendform.php5");
    alert("Your form submission has been saved and will be sent shortly.");
  }
}

function addtocart(productID) {
  	opts = document.getElementById('optionID');
  	optionArray = opts.options[opts.selectedIndex].value;
  	optionValues = optionArray.split(";");
  	optionID = optionValues[1];
  	if (optionID > 0) {
      	num = document.getElementById('qty');
      	qty = num.options[num.selectedIndex].value;
      	coreGetLoop("result", "/addtocart.php5?productID=" + productID + "&optionID=" + optionID + "&qty=" + qty, "optionID", "refreshPage");
      	pageTracker._trackPageview("/addtocart.php5?productID=" + productID);
     	  pageTracker2._trackPageview("/addtocart.php5?productID=" + productID);
      	alert("Product Added to Cart");
  	} else {
  		alert("Please select a color scheme.");
  	}
}

function show(target) {
  div = document.getElementById(target);
  div.style.visibility = "visible";
  div.style.display = "block";
}
  
function hide(target) {
  div = document.getElementById(target);
  div.style.visibility = "hidden";
  div.style.display = "none";
}

function toggle(target) {
  div = document.getElementById(target);
  if (div.style.visibility == "hidden") {
    show(target);
  } else {
    hide(target);
  }
}

function swap(target, imagelink) {
  div = document.getElementById(target);
  div.src = imagelink;
}

function toggleAll(target) {
  toggle(target + "1");
  toggle(target + "2");
  toggle(target + "3");
  toggle(target + "4");
  toggle(target + "5");
  toggle(target + "6");
}

function changeSlide() {
  slide++;
  if (slide > 8) slide = 1;
  var div = document.getElementById("slideshow");
  var imagepath = "images/slide" + slide + ".jpg";
  div.src = imagepath;
  div.width = 958;
  div.height = 200;
  setTimeout ( "changeSlide()", 6000 );
}

function initCarousel() {
  carousel = new YAHOO.widget.Carousel("carousel-2-container", {
	  scrollIncrement: 1, numVisible: 6
  });
  carousel.render();
  carousel.show();
}

function prevSlidePage() {
  if (carousel != null) carousel.scrollPageBackward();
}

function nextSlidePage() {
  if (carousel != null) carousel.scrollPageForward();
}

function initForm() {
  div = document.getElementById("firstName");
  if ((div != null) && (div.disabled == false)) div.focus();
//  div = document.getElementById("subtotal");
//  if (div != null) {
//    total = div.innerHTML;  alert(total);
//    div.innerHTML = "$" + (total + 0).toFixed(2);
//  }
  div = document.getElementById("slide1");
  if (div != null) {
    setTimeout("fade()", 5000);
    //setTimeout ( "changeSlide()", 6000 );
  }
  div = document.getElementById("carousel-2-container");
  if (div != null) initCarousel();
}

function fade() {
    firstSlide = "slide" + (slide % 2 == 1 ? 1 : 2);
    nextSlide = "slide" + (slide % 2 == 1 ? 2 : 1);
    var fadeOut = new YAHOO.util.Anim(firstSlide, { opacity: { to: 0 } }, 1.5);
    slide++; if (slide > maxSlides) slide = 1;
    document.getElementById(nextSlide).src = "/images/slide" + slide + ".jpg";
    var fadeIn = new YAHOO.util.Anim(nextSlide, { opacity: { to: 1 } }, 1.5);
    fadeIn.onComplete.subscribe( setTimeout("fade()", 5000) );
    fadeOut.animate();
    fadeIn.animate();
}

function setAnimation() {
    if (carousel != null) carousel.set("animation", { speed: 1.0 });
}

function checkEnter(e) {
  e = e || event;
  return (e.keyCode || event.which || event.charCode || 0) !== 13;
}

YAHOO.util.Event.addListener(window, "load", initForm);

//YAHOO.util.Event.onDOMReady(initCarousel);

