var autoclose=0;
var autoCloseTime = 120000;
var ErrorOnAjaxAddToCart=false;

function OSAddToCart(theform) {
	var submittedDspValue = theform.Dsp ? theform.Dsp.value : '';
	var submittedSHIPTOValue = theform.SHIPTO ? theform.SHIPTO.value : '';
	var NoConfirmPopup = theform.NoConfirmPopup ? theform.NoConfirmPopup.value : false;
	// autoclose > 0 indicates if an AddToCart is already in progress
	if (autoclose > 0 && !NoConfirmPopup) {return false;}
	if (autoclose > 0 && NoConfirmPopup) { clearTimeout(autoclose); }
	autoclose=1;

	if (submittedSHIPTOValue=='Someone Else') {
		OSShowAddToCartDiv(theform);
		return false;
	}

	theform.Dsp.value='180';
	if (submittedDspValue=='6') {  //Shopping Cart Page
		theform.Dsp.value='181';
	}
	if (submittedDspValue=='160') {  //Custom Combo - customComboForm found on buildacombo_select.xhtml
		document.customComboForm.action = '/servlet/OnlineShopping?NEWSHIPTO=' + theform.NEWSHIPTO.value;
		document.customComboForm.submit();
		return true;
	}

//  if (theform.SHIPTO) {theform.SHIPTO.value = theform.SHIPTO.value.replace(/,/g,"");}
//  if (theform.NEWSHIPTO) {theform.NEWSHIPTO.value = theform.NEWSHIPTO.value.replace(/,/g,"");}
	var queryString = "/servlet/OnlineShopping?" + $(theform).serialize() + "&SubmitDsp=" + submittedDspValue;
	theform.Dsp.value=submittedDspValue;
//  alert(queryString);

	$('#minicart').load(AddOsUrlParms(queryString), { force: 'post' }, function(data){
		if (ErrorOnAjaxAddToCart) { theform.submit(); return; }
		if (NoConfirmPopup) { OSHideAddToCartDiv(); } else { OSShowAddToCartDiv(theform); }
		if (theform.NEWSHIPTO) {
			//replace selects to include new receiver
			$.post(AddOsUrlParms("/servlet/ajax/sacknames?list=all&sort=myself/as_entered&addtoall=false&addnew=false&default="), {force: 'post'}, function(data) {
			var SelectOptions = eval("(" + data + ")");
			var os_selects=document.getElementsByName("SHIPTO");
			var os_select_lastoption;
			for(var i=0;i<os_selects.length;i++) {
				os_select_lastoption = os_selects[i].options[os_selects[i].options.length-1].value;
				os_selects[i].length = 0;
				for(var j=0;j<SelectOptions.length;j++) {
					os_selects[i].options[j]=new Option(SelectOptions[j].sackname,SelectOptions[j].sackname,false,SelectOptions[j].selected);
				}
				if (os_select_lastoption=='Someone Else' || os_select_lastoption=='All Carts') {os_selects[i].options[j] = new Option(os_select_lastoption,os_select_lastoption,false,false);}
			}
			});
		}
	});
	return false;
}

function OSNewRcvrAddToCart(theform,anchor) {
	var submittedNEWSHIPTOValue = theform.NEWSHIPTO ? trimAll(theform.NEWSHIPTO.value) : '';
	if (theform.SubmitDsp) {theform.Dsp.value=theform.SubmitDsp.value;}
	$.post(AddOsUrlParms("/servlet/ajax/validatesack"), {sackname: submittedNEWSHIPTOValue}, function(data) {
	var NewRcvrError = eval("(" + data + ")");
	if (NewRcvrError.isError) {
		$('#NewRcvrError').html(NewRcvrError.message.text);
		$('#NewRcvrError').show();
	} else {
		anchor.innerHTML = '<img src="/gifs/fill.gif" width="65" height="26" border="0" /><img src="/gifs/new/ajax-loader.gif" width="16" height="16" border="0" />'
		OSAddToCart(theform);
	}
	});
}

function OSShowAddToCartDiv(theform) {
	var queryString = '';
	var iid=theform.itemid ? theform.itemid.value : theform.IID.value; //itemid parameter is used for addons
	var submittedDspValue = theform.Dsp ? theform.Dsp.value : '';
	var submittedACTNValue = theform.ACTN ? theform.ACTN.value : '';
	var submittedQTYValue = theform.QTY ? theform.QTY.value : '1';
	var submittedSHIPTOValue = theform.SHIPTO ? theform.SHIPTO.value : (theform.NEWSHIPTO ? theform.NEWSHIPTO.value : '');
	var submittedITMPRCValue = theform.ITMPRC ? theform.ITMPRC.value : '';
	var submittedITMSUFValue = theform.ITMSUF ? theform.ITMSUF.value : '';
	var submittedITMTYPValue = theform.ITMTYP ? theform.ITMTYP.value : '';
	var submittedQuickorderValue = theform.quickorder ? theform.quickorder.value : '';

	if ($('#ErrorBox')[0]) {$('#ErrorBox').hide();}
	if (submittedSHIPTOValue=='Someone Else') {  // Handle New Receivers
		theform.Dsp.value = '183';
		theform.ACTN.value = '';
		theform.IID.value = theform.IID.value.replace(/[^\d]/g, ""); // remove non digits from IID to fix quick order
		autoclose=0;
		queryString="/servlet/OnlineShopping?" + $(theform).serialize() + "&SubmitDsp=" + submittedDspValue;
	} else {
		queryString = "/servlet/OnlineShopping?Dsp=182&IID=" + iid + "&QTY=" + submittedQTYValue + "&SHIPTO=" + escape(submittedSHIPTOValue) + "&ITMSUF=" + submittedITMSUFValue + "&lastsackname=" + escape(submittedSHIPTOValue) + "&ITMTYP=" + escape(submittedITMTYPValue);
		if (submittedQuickorderValue != '') {queryString += "&quickorder=" + submittedQuickorderValue;}
		if (submittedITMPRCValue != '') {queryString += "&ITMPRC=" + submittedITMPRCValue;}
		if (submittedDspValue != '') {queryString += "&SubmitDsp=" + submittedDspValue;}
	}
	theform.Dsp.value = submittedDspValue;
	theform.ACTN.value = submittedACTNValue;

	// Ajax load of content into add to cart popup
	// alert(queryString);
	$('#AddToCartPopup').load(AddOsUrlParms(queryString), { force: 'post' }, function(data){

		if (ie) { $('select').hide(); } //fix ie bug of select tags showing through popup div
		// Handle width and height of faded "blanket" div
		$('#Blanket').css('width', getPageSizeWithScroll()[0] + 'px');
		$('#Blanket').css('height', getPageSizeWithScroll()[1] + 'px');
		if ($('#itemsuggestions').length > 0) { //Only applies to SKU page
			$('#upsells').show();
			$('#crosssells').hide();
		}
		$('#AddToCartPopup')[0].style.left=Math.max(0,getScrollXY()[0] + (getPageSize()[0]/2) - ($('#AddToCartPopup')[0].offsetWidth/2));
		$('#AddToCartPopup')[0].style.top=Math.max(0,getScrollXY()[1] + (getPageSize()[1]/2) - ($('#AddToCartPopup')[0].offsetHeight/2));
		$('#Blanket').css('backgroundPosition','-100px -100px');
		$('#Blanket').show();
		$('#AddToCartPopup')[0].style.visibility="visible";
		if (submittedSHIPTOValue!='Someone Else') { //Set popup to close automatically if not a new receiver popup
			if (submittedSHIPTOValue == 'All Carts' || submittedITMTYPValue == '4') {autoCloseTime = 5000;}
			autoclose = setTimeout("OSHideAddToCartDiv('autoclose');",autoCloseTime);
		}
	  if (submittedITMTYPValue == '15' || submittedITMTYPValue == '16' ) { // if a gift card is purchased, automatically mark the shipment as a gift shipment
	    $.ajax({
	    	url: AddOsUrlParms("/servlet/OnlineShopping?ACTN=72&Dsp=1000&GIFTINDICATOR=true&isGift=on&SACKNAME=" + submittedSHIPTOValue),
	    	type: "POST",
	    	success: function(){ },
	    	error: function(){ }
	    });
	  }
	});
}

function OSShowConstrainedUpsells(divobj) {
	$('#AddToCartPopup').html(divobj.html());
	if (ie) { $('select').hide(); } //fix ie bug of select tags showing through popup div
	// Handle width and height of faded "blanket" div
	$('#Blanket').css('width', getPageSizeWithScroll()[0] + 'px');
	$('#Blanket').css('height', getPageSizeWithScroll()[1] + 'px');
	$('#AddToCartPopup')[0].style.left=(getPageSize()[0]/2) - ($('#AddToCartPopup')[0].offsetWidth/2);
	$('#AddToCartPopup')[0].style.top=Math.max(0,getScrollXY()[1] + (getPageSize()[1]/2) - ($('#AddToCartPopup')[0].offsetHeight/2));
	$('#Blanket').css('backgroundPosition','-100px -100px');
	$('#Blanket').show();
	$('#AddToCartPopup')[0].style.visibility="visible";
	return false;
}

function OSHideAddToCartDiv(mode) {
	if (typeof unsavedChanges != 'undefined') { unsavedChanges = true; }  // used in buildacomboselect.xhtml
	$('#Blanket')[0].style.display="none";
	$('#AddToCartPopup')[0].style.visibility="hidden";
	$('#AddToCartPopup')[0].innerHTML="";
	if (ie) {
		$('select').show();
	}
	if (mode!='autoclose') {clearTimeout(autoclose);}
	autoclose=0;
	autoCloseTime = 120000;
	return false;
}

function OSRefuseUpsell(refuseSack) {
	$.post(AddOsUrlParms("/servlet/ajax/refuseupsell"), {sackname: refuseSack}, function(data) {
		return OSHideAddToCartDiv();
	});
}

function OSRefreshMinicart(theform) {
	theform.Dsp.value = '180';
	var queryString = "/servlet/OnlineShopping?" + $(theform).serialize();
	$('#minicart').load(AddOsUrlParms(queryString), { force: 'post' }, function(data){
		return false;
	});
	return true;
}

function submitGiftIndicatorForm(changeObj) {
	if (changeObj.checked) {
		if (changeObj.id=='isGift') {
			$("#isNotGift").removeAttr('checked');
			$("input[name=GIFTINDICATOR]").attr('value','true');
		} else {
			$("#isGift").removeAttr('checked');
			$("input[name=GIFTINDICATOR]").attr('value','false');
		}
	} else {
		$("input[name=GIFTINDICATOR]").attr('value','');
	}
	$.ajax({
		url: AddOsUrlParms("/servlet/OnlineShopping?" + $("#giftIndicatorForm").serialize()),
		type: "POST",
		success: function(){ },
		error: function(){ }
	});

}

