/* vim: set noexpandtab: */
// this file assumes that xml.js has been loaded
//  DEFAULT VARIABLES
var i = 0;
var currentTab = 'product';
var currentItem = 0;
var item_cost = 0.00;
var shipping_cost = 0.00;
var numRecipients = 1;
var qty = 1;
var defaultQty = 1;
var defaultMessage = '';
var recipientArray = new Array();
var currentRecipient = null;
var currentRecipientNum = 0;
var formDataDiv = null;
var custom_flavor = new Array( false, false, false );
var fieldArray = new Array('fname', 'lname', 'company', 'address1', 'address2', 'city', 'state', 'zip', 'phone1', 'phone2', 'phone3', 'rec_qty', 'gift_message', 'gm_none', 'delivery_date', 'shipping_method', 'pers_message' );
var edit_mode = false;
var defaultFlavors = new Array();
var default_special = 0;
var show_special = true;
var deserve = false;
var messageCheckVal = "1";
var clickHistory = "";
var offerUpgradeItemId = 0;
var typeNum;
var num_flavor_groups = 0;
var checkboxCount = 0;
var checkboxMax = 0;
var tokenIndex = 0;
var productImg = '';
var hit_recip_tab = 0;
var cart_content_count = 0;
var omn_page_name = "";
var omn_event_num = "0";
var omn_event_add = "";
var omn_specials_list = "";
var product_idx;
var multi_express_ab_test = 0;
var google_checking_out = false;
var selected_lineitems = new Array();

defaultFlavors[ '0' ] ='';
defaultFlavors[ '1' ] ='';
defaultFlavors[ '2' ] ='';

//  OMNITURE CUSTOM LINKING FUNCTION
	function omniture_custom_link( tab_name ) {
		if ( typeof( s ) != 'undefined' ) {

			//  Set the event number.
			omn_page_name = "";
			omn_event_num = "";
			omn_event_add = "";

			if( tab_name == "product" ) {
				omn_page_name = "Details";
				omn_event_num = "3";
			} else if( tab_name == "recipient" ) {
				omn_page_name = "Recipient";
				hit_recip_tab++;
				omn_event_num = "4";
				if( cart_content_count == 0 && hit_recip_tab == 1 ) {
					omn_event_add = ",scOpen,scAdd";
				} else {
					omn_event_add = ",scAdd";
				}
			} else if( tab_name == "shipping" ) {
				omn_page_name = "Shipping";
				omn_event_num = "5";
			} else if( tab_name == "add_on" ) {
				omn_page_name = "Upsell";
				omn_event_num = "8";
			}

			if( omn_event_num != "" && omn_event_num != "0" ) {

				s.linkTrackVars = "events,pageName";
				s.pageName="gifts : " + omn_page_name
				s.linkTrackEvents = "event" + omn_event_num + omn_event_add;
				s.events = "event" + omn_event_num + omn_event_add;

				if( omn_event_num == 8 && omn_specials_list.length != 0 ) {
					s.linkTrackVars = s.linkTrackVars + ",products";
					s.products = omn_specials_list;
				}
			}
			s.tl( true, 'o', "Product: " + omn_page_name );
		}
	}

	// Custom Greeting card Functions
	function pad(string, padding, length){
		var tempString = "";
		var numChars = length - string.length;
		var i = 0;
		while(tempString.length < numChars){
			tempString +=padding;
		}
		tempString+=string;
		return tempString;
	}

	function get_custom_greeting_card_token() {

		// is there a token set?
		var tokenEl = document.getElementById('custom_greeting_card');
		if( tokenEl && tokenEl.value ) {
			return tokenEl.value;
		}

		// make a new token.
		tokenIndex++;
		var token = base_token.concat(pad(tokenIndex.toString(),'0',3));
		if( tokenEl ) {
			tokenEl.value = token;
		}
		return token;

	}

	function save_greeting_card(token, edit_url){
		hide_greeting_card_layers();
		var el = document.getElementById('custom_greeting_card');
		var url = document.getElementById('edit_url');
		if( url && el && token ) {
			el.value = token;
			url.value = edit_url;
			display_greeting_card();
		}
	}

	function display_greeting_card(){

		var greeting_card_checkbox_content = document.getElementById('custom_greeting_card_checkbox_content');
		var greeting_card_options = document.getElementById('greeting_card_options');
		var msg = document.getElementById('message');

		if(greeting_card_checkbox_content){
			if( 1 || currentRecipient.has_greeting_card ) {
				var tempString = "<br /><span class=\"bold\">This recipient has been assigned a<br />personalized greeting card.</span> You may:<br /><ul>" + get_delete_custom_greeting_card() + " " + get_edit_custom_greeting_card() + "</ul>";
				greeting_card_checkbox_content.innerHTML=tempString;
				greeting_card_checkbox_content.style.display="block";
				greeting_card_options.style.display="none";
				msg.style.display="none";
			} else {
				greeting_card_checkbox_content.style.display="none";
				greeting_card_options.style.display="block";
				msg.style.display="block";
			}
		}
	}

	function show_greeting_card_layers() {
		var url = custom_greeting_card_post_url.replace(/%token%/, get_custom_greeting_card_token());
		openWindow('custom_greeting',url,810,640,1);
	}

	function get_delete_custom_greeting_card(){
		return "<li><a class=\"nobold red\" href=\"javascript: delete_custom_greeting_card('"+ get_custom_greeting_card_token() +"')\">Delete the greeting card.</a></li>";
	}

	function get_edit_custom_greeting_card(){
		var url = custom_greeting_card_post_url.replace(/%token%/, get_custom_greeting_card_token());
		return "<li><a class=\"nobold red\" href=\"javascript:openWindow('custom_greeting','" + url + "',810, 580,1)\">Edit the greeting card.</a></li>";
	}

	function show_has_greeting_card(){
		display_greeting_card();
	}

	function hide_greeting_card_layers(){
		var greeting_card_layer = document.getElementById('custom_greeting_card');
		if(greeting_card_layer){
			greeting_card_layer.style.display="none";
		}
	}

	function delete_custom_greeting_card(token){
		var tokenEl = document.getElementById('custom_greeting_card');
		if( tokenEl ) {
			tokenEl.value = '';
		}

		var greeting_card_checkbox_content = document.getElementById('custom_greeting_card_checkbox_content');
		var greeting_card_options = document.getElementById('greeting_card_options');
		var msg = document.getElementById('message');
		if(greeting_card_checkbox_content){
			greeting_card( 'Product', 'form[gm_standard]' );
			greeting_card_checkbox_content.style.display="none";
			greeting_card_options.style.display="block";
			msg.style.display="block";
			greeting_card( 'none' );

			var del_field = document.forms[ 'Product' ].elements[ 'form[delete_custom_greeting_card]' ];
			if( del_field ) {
				del_field.value = 1;
			}
		}
	}

//  ITEM HOVER AND ONLICK EVENTS
	var over = 'DDDDDD';
	var out = 'FFFFFF';
	var click = 'BFBFBF';
	var click_text = 'FFFFFF';
	var clear_text = '6E6E6E';

	var selectedId = '';
	function changeOver( id ) {
		if( items[id] == false ){
			if(selectedId)changeOut(selectedId);
			document.getElementById( "item_" + id ).style.backgroundColor = "#" + over;
			selectedId = id;
		}
			var fullNameDiv = document.getElementById( "item_full_" + id );
			if( fullNameDiv){
				fullNameDiv.style.display = "block";
			}
	}

	function changeOut( id ) {
		if( items[id] == false ){
			document.getElementById( "item_" + id ).style.backgroundColor = "#" + out;
		}
			var fullNameDiv = document.getElementById( "item_full_" + id );
			if( fullNameDiv){
				fullNameDiv.style.display = "none";
			}
	}

	function selectItem( item_idx ) {

		//  Hide all currently displayed items.
		var flavors = getElementsByStyleClass( 'flavor_holder' );

		if( flavors && flavors.length > 0 ) {
			for( var i = 0; i < flavors.length; i++ ) {
				flavors[i].style.display = "none";
			}
		}

		//  Show the flavors for this item.
		var tom = document.getElementById( 'flavors_' + item_idx );
		if( tom ) {
			tom.style.display = "block";
		}

		//  Select the radio button.
		var rad_flav = document.getElementById( 'radio_' + item_idx );
		if( rad_flav ) {
			rad_flav.checked = true;
		}

		//  Item image override?
		if( typeof( item_images ) != "undefined" ) {
			if( item_images && item_images[ item_idx ] ) {
				$("#item_image").attr( "src", item_images[ item_idx ].src );
			}
		}

	} // end selectItem

	// move the selected standard greeting, or the custom greeting to the hidden field that is error checked.
	function saveMessage( ) {
		var selectDiv = document.getElementById('deco_select_box');
		var custom = document.forms.Product['form[pers_message_fake]'];
		var finalMessage = document.forms.Product['form[pers_message]'];
		var currentStandard = '';
		if( selectDiv.options.length > 0 ) {
			currentStandard = selectDiv.options[selectDiv.selectedIndex].value;
		}

		if( currentStandard != '' ) {
			custom.value = '';
			custom.disabled = true;
			finalMessage.value = currentStandard;
		} else {
			custom.disabled = false;
			finalMessage.value = custom.value;
		}

	}

	function showSentiments( item_idx ) {

		var sentimentDiv = document.getElementById('sentiments');
		if(!sentimentDiv)
			return;

		sentimentDiv.innerHTML = '';
		var sentiment_temp = '';
		var sentiment_html = '';
		var clickImage = '';
		var callback = '';

		var i = 0;
		while(i < sentiments.length) {

			if( product_items[item_idx ]['sentiments_display'] == 1 ) {
				clickImage = 'onclick="clickSentimentImage('+i+');"';
				callback = ' clickSentimentImage('+i+');';
			}

			sentiment_temp = sentiment_detail_template.replace(/%code%/g,sentiments[i]['idx']);
			sentiment_temp = sentiment_temp.replace(/%selected%/g,'');
			sentiment_temp = sentiment_temp.replace(/%checked%/g,'');
			sentiment_temp = sentiment_temp.replace(/%name%/g,sentiments[i]['title']);
			sentiment_temp = sentiment_temp.replace(/%counter%/g,i);
			sentiment_temp = sentiment_temp.replace(/%img%/g,'/'+sentiments[i]['img']);
			sentiment_temp = sentiment_temp.replace(/%callback%/g,callback);
			sentiment_temp = sentiment_temp.replace(/%clickimage%/g,clickImage);
			sentiment_html += sentiment_temp;
			i++;
		}

		var msg = "Please select a " + sentiments['title'];
		var sentiment_content = '';
		sentiment_content = sentiment_main_template.replace(/%label%/g,sentiments['title']);
		sentiment_content = sentiment_content.replace(/%sentiments%/g,sentiment_html);
		sentiment_content = sentiment_content.replace(/%recip%/g,'');
		sentiment_content = sentiment_content.replace(/%click_id%/g,'2');
	 	sentiment_content = sentiment_content.replace(/%callback%/g,'');
		sentiment_content = sentiment_content.replace(/%arrow%/g,'<img class="arrow" src="/images/error_arrows/error_arrow_l.gif" alt="" />');
		sentiment_content = sentiment_content.replace(/%error_helper%/g,'');
		sentiment_content = sentiment_content.replace(/%error_msg%/g, msg );
		sentiment_content = sentiment_content.replace(/%first_line%/g,'- select -');
		sentimentDiv.innerHTML = sentiment_content;

		var sentiments_div = document.getElementById( "sentiments" );
		if(sentiments_div){
			if ( product_items[item_idx]['sentiments_require'] == 1 || product_items[item_idx]['sentiments_display'] == 1) {
				sentiments_div.style.display = "block";
			} else {
				sentiments_div.style.display = "none";
				if( product_items[item_idx ]['sentiment_display'] == 1 || sentiments['idx'] == '10' ) {
					document.forms.Product['form[sentiment]'].selectedIndex = '';
				} else {
					document.forms.Product['form[sentiment]'].value = '';
				}
			}
		}
	}

	function changeArrow( on, off1, off2 ) {
		var on_el = document.getElementById( on + "_image" ); on_el.src = "/images/menu_arrow_on.gif";
		var off1_el = document.getElementById( off1 + "_image" ); off1_el.src = "/images/menu_arrow_off.gif";
		var off2_el = document.getElementById( off2 + "_image" ); off2_el.src = "/images/menu_arrow_off.gif";
	}

//  FLAVOR SELECTIONS
	function SetValue( ele, value ){
		eval(ele+"='';");
		eval(ele+"+='"+ value +"';");
	}

	function SetFlavorSelection( type ) {
		var flavor = '';
		// get the flavor group this is for. no longer just cookies.
		var typeNum = type.replace("type","");

		var flavor_select = document.getElementById( 'type' + type + "_flavors" );
		// select box
		if(flavor_select){
			flavor = flavor_select.options[flavor_select.selectedIndex].value;

		// radio buttons (the id above doesn't exist when using the image/radio button selection type)
		} else {
			flavor_select = document.forms.Product['form[flavor_type'+type+']'];
			if( flavor_select) {
				for(var i = 0; i < flavor_select.length; i++) {
					if(flavor_select[i].checked) {
						flavor = flavor_select[i].value;
						break;
					}
				}
			}
		}

		var group = product_items[ currentItem  ]['flavor_group'][ typeNum ]['flavor_group_idx'];

		// show custom flavor selection
		if( flavor == "CU") {
			custom_flavor[typeNum] = true;
			if(edit_mode) {
				openWindow( 'custom_flavors', '/gifts/custom_flavors.mfc?typeNum='+typeNum+'&group='+ group +'&idx='+currentItem+'&recipient=1' , 400, 475, 0 )
			} else {
				openWindow( 'custom_flavors', '/gifts/custom_flavors.mfc?typeNum='+typeNum+'&group='+ group +'&idx='+currentItem, 400, 475, 0 )
			}

		} else {
			custom_flavor[typeNum] = false;
			defaultFlavors[ type ] = '0:' + flavor;
			for(var i=0; i < recipientArray.length; i++) {
				recipientArray[i].flavors[typeNum]['flavor_code'] = '0:' + flavor;
			}
		}
	}

	function SetRecipFlavorSelection( typeNum ) {

		var flavor_element;
		var flavor;
		if( product_items[currentItem ]['flavor_display'] == 1 ) {
			flavor_element = document.forms.Product['form[recip_flavor_type'+ typeNum +']'];
			for(var i=0;i<flavor_element.length;i++) {
				if( flavor_element[i].checked == true ) {
					flavor = flavor_element[i].value;
					break;
				}
			}
		} else {
			flavor_element = document.getElementById( "recip_type"+ typeNum +"_flavors" );
			flavor = flavor_element.options[flavor_element.selectedIndex].value;
		}

		var type = product_items[currentItem]['types'][ typeNum ];
		var group = product_items[ currentItem  ]['flavor_group'][ typeNum ]['flavor_group_idx'];

		if( flavor == "CU") {
			custom_flavor[typeNum] = true;
			eval('currentRecipient.custom_' + typeNum + ' = 1;');
			openWindow( 'custom_flavors', '/gifts/custom_flavors.mfc?typeNum='+ typeNum +'&group='+ group +'&idx='+currentItem+'&recipient='+(currentRecipientNum+1), 400, 475, 0 );
			document.forms.Product['form[flavor_type'+ typeNum +']'].value = 'CU';
		} else {
			custom_flavor[typeNum] = false;
			recipientArray[currentRecipientNum].flavors[typeNum]['flavor_code'] = + flavor;
			document.forms.Product['form[flavor_type'+ typeNum +']'].value = flavor;
		}

	}

//  PRODUCT ITEM/FLAVOR FORM VALIDATION
	function gift_express_checkout( form ) {
		var el = document.getElementById( 'express_checkout' );
		if( multi_express_ab_test == 0 && el ) {
			el.value = 1;
		}

		check_item( form );
	}

//  CHECK THE ITEM
	function check_item( form_name ) {

		if( offerUpgradeItemId > 0 ) {
			document.getElementById('upgrade_data').style.display = 'block';
			document.getElementById('upgradeOffered').value = 1;
			return;
		}
		var recips = document.forms[form_name]['form[recips]'];
		var qtyDiv = document.forms[form_name]['form[qty]'];

		if(qtyDiv.value == '')
			qty.value = 1;

		setQuantity(document.forms[form_name]['form[qty]'].value);

		//__updateDefaultQty();
		if( validate_item( form_name ) ) {
			is_complete( form_name, 'product' );
			ClearAll( form_name );

			if( !google_checking_out && submit_once() ) {
				document.forms[form_name].submit();
			}
		}
	}

	function validate_item( form_name ) {

		//  Clear ALL validation.
		Reset();
		ClearAll( form_name );

		var form = document.forms['Product'];

		//  Require the item.
		AddValidationField( form_name, 'form[item]', '[1-9]', 'item_err' );
		AddValidationField( form_name, 'form[qty]', '^[1-9][0-9]*$', 'qty_err' );

		//  Require the personal message?
		var pers_msg = product_items[ document.forms[ form_name ].elements[ 'form[item]' ].value ][ 'pers_messages' ];
		AddValidationField( form_name, 'form[pers_message]', '[0-9a-zA-Z]+', 'pers_message_err', false );
		if( pers_msg == "1" ) {
			AddValidationField( form_name, 'form[pers_message]', '[0-9a-zA-Z]+', 'pers_message_err', true );
		}

		//  Clear validation for flavors.
		for( var i = 0; i < num_flavor_groups; i++ ) {
			AddValidationField( form_name, 'form[flavor_type'+ i +']', '[0-9a-zA-Z+]', 'ftype' + i + '_err', false );
		}

		//  Require the sentiment? (can't check until an item is selected)
		if( currentItem && product_items[currentItem]['sentiments_require'] == 1 ){
			AddValidationField( form_name, 'form[sentiment]', '[1-9]', 'sent_err' );
		}

		//  Validate the form.
		if( Validate( form_name ) ) {
			return true;
		} else {
			return false;
		}
	}

//  RECIPIENT DATA FORM VALIDATION
	function check_recip( form_name ) {
		is_complete( form_name, 'recipient' );
		ClearAll( form_name );

	}


	function validate_recip_name( form_name ) {

		//  Clear ALL validation.
		Reset();
		ClearAll( form_name );

		AddValidationField( form_name, 'form[fname]', '[a-zA-Z]+', 'pers_greeting_err' );
		AddValidationField( form_name, 'form[lname]', '[a-zA-Z]+', 'pers_greeting_err' );

		//  Validate the form.
		if( Validate( form_name ) ) {
			return Validate( form_name );
		}
		return false;

	}

//  SHIPPING DATA FORM VALIDATION
//  SUBMIT THE FORM!
	function check_shipping( form_name ) {

		//  Clear ALL validation.
		highlight_method = true;
		outline_method = false;
		Reset();
		ClearAll( form_name );

		if( validate_shipping( form_name ) ) {
			is_complete( form_name, 'shipping' );
		}
	}

	function validate_shipping( form_name ) {

		// loop through each gift that is checked and add validation.
		var i = 0;
		var date_name;
		var item_date_val;
		var method_name;
		var unchecked = 0;
		var first_lineitem = "";

		// each item in the cart, skip if not checked.
		while( i < lineitems.length ) {

			var checkbox = document.getElementById('lineitem_' + lineitems[i] );
			var express = document.getElementById('express_checkout');
			if( (!checkbox || !checkbox.checked) && (!express || express.value!=1) ) {
				unchecked++;
				i++;
				continue;
			}

			// get the names of the fields for this item.
			date_name = "lineitems[" + lineitems[i] + "][delivery_date]";
			method_name = "lineitems[" + lineitems[i] + "][ship_method]";
			msg_name = "lineitems[" + lineitems[i] + "][pers_message]";
			check_box = "lineitems[" + lineitems[i] + "][send_to]";

			//  Validate the Shipping date
			AddValidationField( form_name, date_name, '[1-9]+', 'ship_date_err_' + lineitems[i] );

			var pers_box = document.getElementById( 'pers_message_field_' + lineitems[i] );
			if( pers_box ) {
				AddValidationField( form_name, msg_name, '[a-zA-Z]', 'per_msg_err_' + lineitems[i] );
			}

			// if there is a shipping date, Validate the Shipping method.
			item_date_val = document.forms[form_name][date_name].value;
			if ( item_date_val != null && item_date_val != "" ) {
				AddValidationField( form_name, method_name, '[a-zA-Z]{3}', 'ship_method_err_' + lineitems[i] );
			}

			i++;
		}

		//  Validate the form.
		if( Validate( form_name ) ) {
			return true;
		} else {
			return false;
		}
	}

//  CHECK FOR FORM COMPLETION AND SUBMIT IF NO ERRORS ARE FOUND
	var is_submitted = false;
	function is_complete( form_name, no_check ) {

		//  Clear ALL validation.
		ClearAll( form_name );

		//  Check the data from the 'item/flavors' tab.
		if( no_check != 'product' ) {
			if( !validate_item( form_name ) ) {
				activate( 'product' );
				return false;
			}
		}

		//  Check the data from the 'recipient/card message' tab.
		if( no_check != 'recipient' ) {
			if( recipientArray.length != numRecipients) {
				activate( 'recipient' );
				return false;
			}else{
				if( !validate_recip( form_name ) ){
				activate( 'recipient' );
				return false;
				}
			}
		}

		//  Check the data from the 'shipping' tab.
		if( no_check != 'shipping' ) {
			if( !validate_shipping( form_name ) ) {
				activate( 'shipping' );
				return false;
			}
		}

		// make sure each recipient has a delivery and ship date
		for (i = 0; i < numRecipients; ++i){
			if(!recipientArray[i].delivery_date || !recipientArray[i].ship_date){
				currentRecipientNum = i;
				currentRecipient = recipientArray[currentRecipientNum];
				__populate_form(currentRecipient);
				activate( 'shipping' );
				return false;
			}
		}
		//  Submit the form.
		if(!is_submitted){
			 __update_form_recipients();
			document.forms[ form_name ].submit();
			is_submitted = true;
		}
		return true;
	}

//  SUBMIT FORM (WITHOUT DATAVALIDATION) AND SAVE DATA INTO THE SESSION FOR USE LATER
	function submitAndSave( form_name, place, catalog, gift_circle ) {
		var return_url = "/gifts/" + document.forms[ form_name ].elements[ 'form[url_id]' ].value + "?place=" + place + "&catalog=" + catalog + "&gift_circle=" + gift_circle;
		__update_form_recipients();
		document.forms[ form_name ].elements[ 'form[save_into_session]' ].value = "1";
		document.forms[ form_name ].elements[ 'redirect' ].value = "/account/login/?redirect=" + escape( return_url ).replace(/\+/g, '%2C').replace(/\"/g,'%22').replace(/\'/g, '%27').replace(/\//g, '%2F').replace(/\?/g, '%3F') + "&reclaim_product=true";
		document.Product.submit();
	}

// GOTO FORYOURSOUL
	function ForYourSoul( ) {
		var form_name = 'Product';
		var return_url = "/gifts/" + document.forms[ form_name ].elements[ 'form[url_id]' ].value + "?place=recipient";
		__update_form_recipients();
		document.forms[ form_name ].elements[ 'form[save_into_session]' ].value = "1";
		document.forms[ form_name ].elements[ 'redirect' ].value = " /gifts/4yoursoul/?redirect=" + escape( return_url ).replace(/\+/g, '%2C').replace(/\"/g,'%22').replace(/\'/g, '%27').replace(/\//g, '%2F').replace(/\?/g, '%3F') + "&reclaim_product=true&4yoursoul=true&recipient_num="+currentRecipientNum;
		document.forms[ form_name ].elements[ 'form[4yoursoul]' ].value = true;
		document.Product.submit();
	}

//  RECIPIENT DATA
	function Recipient( fname, lname, company, address1, address2, city, state, zip, phone1, phone2, phone3, rec_qty, gift_message, gm_none, delivery_date, shipping_method, lineitem_idx, recipient_id, pers_message, flavors, messageCheck, special, custom_greeting_card_token ) {

		var field = '';
		for(var i=0; i<fieldArray.length; i++){
			field  = fieldArray[i];
			eval("this."+field+" = eval(field+\"?\"+field+\":''\");");
		}

		this.delivery_date = delivery_date?delivery_date * 1000:0;
		this.Update = __updateRecipient;
		this.UpdateDelivery = __updateRecipientDelivery;
		this.lineitem_idx = lineitem_idx?lineitem_idx:'';
		this.recipient_id = recipient_id?recipient_id:'';

		if(flavors){
			this.flavors = flavors;
		}else{
			this.flavors = new Array();
		}

		for( var i=0; i < num_flavor_groups; ++i ) {
			if(!this.flavors[i]) {
				this.flavors[i] = new Array();
			}
			if(flavors && flavors[i]){
				this.flavors[i] = flavors[i];
			}else{
				if(defaultFlavors[i]){
					if(custom_flavor[i]){
					  this.flavors[i]['flavor_code'] = 'CU';
					  this.flavors[i]['custom_flavor'] = defaultFlavors[i];
					}else{
					  this.flavors[i]['flavor_code'] = defaultFlavors[i];
					}
				}
			}
//      this.flavors[i] = flavors?flavors[i]:(defaultFlavors[i]?defaultFlavors[i]:0);
		}

		this.special = special?special:default_special;
		this.custom_greeting_card_token = custom_greeting_card_token;
		this.messageCheck = messageCheck?messageCheck:"1";
		if(this.messageCheck == 2)
			this.has_greeting_card = 1;
	}

	function updateFlavors( recipNum, flavorString, all, typeIndex ) {
		if(recipientArray && recipientArray.length > 0) {
			if( all ) {
				for (i = 0; i < numRecipients; ++i){
					recipientArray[ i ].flavors[typeIndex]['custom_flavor'] = flavorString;
					recipientArray[ i ].flavors[typeIndex]['flavor_code'] = "CU";
				}
			}else{
				recipientArray[ recipNum ].flavors[typeIndex]['custom_flavor'] = flavorString;
				recipientArray[ recipNum ].flavors[typeIndex]['flavor_code'] = "CU";

			}
		}
	}

	function setNumberRecipients(num){
		numRecipients = parseInt(num);
		if(numRecipients == 0)
			numRecipients = 1
		recipientArray = recipientArray.slice(0,numRecipients);
		__update_recip_desc();
	}

	function setQuantity(num){
		qty = parseInt(num);
		if (qty ==0) qty=1;

	}

	function  __updateDefaultQty(){
		defaultQty = Math.floor(qty / numRecipients);
		if(defaultQty < 1)
			defaultQty = 1;
		document.forms['Product']['form[rec_qty]'].value = defaultQty;
	}

	var going_dir = 0;
	function PreviousRecipient() {
		going_dir = -1;

		if (view_flavors){
			closeFlavorDiv();
			return;
		}
		if( currentRecipientNum == 0){
			UpdateRecipient();
			activate( 'product' );
			return;
		}else{
			if (!UpdateRecipient()){
				return;
			}
			if( currentRecipientNum == 0){
				activate( 'product' );
				return;
			}
			currentRecipientNum--;
			if(!recipientArray[currentRecipientNum]){
				recipientArray[currentRecipientNum] = new Recipient();
			}
			currentRecipient = recipientArray[currentRecipientNum];
			__populate_form(currentRecipient);
		}
		__update_recip_desc();
	}

	var abort_special = false;

	function NextRecipient(goto_special) {

		return; // shouldn't need this anymore

		going_dir = 1;
		abort_special = false;
		if (view_flavors){
			closeFlavorDiv();
			return;
		}
		if (!UpdateRecipient()){
			return;
		}
		save_recipients();
		if(false && currentRecipient.messageCheck==2 && !currentRecipient.fouryoursoul_completed && !edit_mode){
			ForYourSoul();
			return;
		}
		if(goto_special && show_special && !abort_special){

			var spec_name = document.getElementById( 'special_recip_name' );
			if( spec_name ) spec_name.innerHTML = document.forms[ 'Product' ].elements[ 'form[fname]' ].value;

			activate('add_on');
			return;
		}else{
			if( currentRecipientNum == (numRecipients - 1)){
				currentRecipientNum = 0;
				currentRecipient = recipientArray[currentRecipientNum];
				__populate_form(currentRecipient);
				activate( 'shipping' );
				return;
			}
			activate('recipient');
			//__populate_form(currentRecipient);
		}
		if( currentRecipientNum == (numRecipients - 1)){
			currentRecipientNum = 0;
			currentRecipient = recipientArray[currentRecipientNum];
			__populate_form(currentRecipient);
			activate( 'shipping' );
			return;
		}else{
			currentRecipientNum++;
			if(!recipientArray[currentRecipientNum]){
				recipientArray[currentRecipientNum] = new Recipient();
				if(currentRecipientNum == numRecipients - 1){
					recipientArray[currentRecipientNum].rec_qty = Math.floor( qty / numRecipients ) + qty % numRecipients;
				}
			}
			currentRecipient = recipientArray[currentRecipientNum];
			__populate_form(currentRecipient);
		}
		__update_recip_desc();
	}

	function UpdateRecipient(){

		return; // shouldn't need this anymore

		if(going_dir == -1 && __is_form_blank()) {
			return true;
		}
		if(recipientArray.length > 1 && __is_form_blank() ){
			var result = true;
			if(going_dir > 0){
				result = confirm('You originally specified ' + numRecipients + ' recipients, but have only entered ' + (recipientArray.length - 1) +' so far.\nIf you would like to continue with recipients ' + recipientArray.length + ' - ' + numRecipients + ' click "ok".\nOtherwise click "cancel"');
				if (result) return false;
			}
			setNumberRecipients(recipientArray.length - 1);
			currentRecipientNum = numRecipients - 1;
			currentRecipient = recipientArray[currentRecipientNum];
			abort_special = true;
		}else{
			if(validate_recip( 'Product' )){
				if(typeof(recipientArray[currentRecipientNum])=='undefined'){
					recipientArray[currentRecipientNum] = new Recipient();
				}
				currentRecipient = recipientArray[currentRecipientNum];
				currentRecipient.Update();
				if(document.forms['Product']['form[same_message]'].checked){
					var tempRecipient = null;
					for(var i=0; i < recipientArray.length; i++ ){
					  tempRecipient = recipientArray[i];
					  var message = document.forms['Product']['form[gift_message]'].value;
					  tempRecipient.gift_message = message;
					  defaultMessage = message;
					}
				}
			}else{
				return false;
			}
		}
		return true;
	}

	function __update_recip_desc(){
		var div = document.getElementById('recip_desc');
		var div2 = document.getElementById('recip_flavor_desc');
		var innerHTML = '';
		if(numRecipients > 1) {
				innerHTML = '<h4>Recipient - #' + (currentRecipientNum+1) +' (of ' + numRecipients + ')</h4>';
		}else{
				innerHTML ='<h4>Recipient Info:</h4>';
		}
		if (div) div.innerHTML = innerHTML;
		if (div2) div2.innerHTML = innerHTML;
	}

	function __populate_form(recipient){
		var tempForm = document.forms['Product'].elements;
		var field=''
		if(recipient){
			for(var i=0; i<fieldArray.length; i++){
				field  = fieldArray[i];
				if(field != 'shipping_method' && field != 'delivery_date'){
					if(eval("tempForm['form["+field+"]']")){
					  eval("tempForm['form["+field+"]'].value = eval(\"recipient.\"+field);");
					}
				}
			}
			deliveryDate = new Date(recipient.delivery_date);
		}
		if(!tempForm['form[rec_qty]'].value){
			tempForm['form[rec_qty]'].value = defaultQty;
		}
		if(!tempForm['form[gift_message]'].value){
			tempForm['form[gift_message]'].value = defaultMessage;
		}
		if(tempForm['recipients']){
			tempForm['recipients'].value = '';
		}
		var tempDiv = document.getElementById('edit_cnt');
		if (!tempDiv) return;
		if(has_flavors){
			tempDiv.style.display = 'block';
		}else{
			tempDiv.style.display = 'none';
		}
		var gm = tempForm[ 'form[gift_message]' ];
		var sm = tempForm[ 'form[gift_message]' ];
		var gm_custom = tempForm[ 'form[gm_custom]' ];
		var gm_standard = tempForm[ 'form[gm_standard]' ];
		var gm_none = tempForm[ 'form[gm_none]' ];

		if(gm) {
			gm.disabled = true;
			gm.style.background = "#D4D0C8";
		}

	messageCheckVal = recipient.messageCheck;

		if(sm) sm.disabled = true;
		if(gm_custom) gm_custom.checked = false;
		if(gm_standard) gm_standard.checked = false;
		if(gm_none) gm_none.checked = false;

		switch(recipient.messageCheck){
			case "0":
				if(gm_none) { gm_none.checked = true; }
				break;
			case "1":
				if(sm)sm.disabled = false;
				if(gm){
					gm.disabled = false;
					gm.style.background = "#FFF";
				}
				if(gm_standard) gm_standard.checked = true;
				break;
			case "2":
				if(gm_custom) gm_custom.checked = true;
				break;
		}
			display_greeting_card();
	}

	function __update_form_recipients(recipient) {

		if(!formDataDiv)
			formDataDiv = document.getElementById('recip_form_data');
		var customFlavors  = document.forms['Product']['form[custom_flavor]'];

		for(var i=0; i < num_flavor_groups; ++i){

			if(custom_flavor[i]) {
		    customFlavors.value = defaultFlavors[i];
			}
		}

		var innerHTML = '';
		var tempRecipient = null;
		var field = '';
		var flavType = '';

		for(var i=0; i < recipientArray.length; i++){
			tempRecipient = recipientArray[i];
			for(var j=0; j < fieldArray.length; j++){
				field  = fieldArray[j];
				if (fieldArray[j] == 'gift_message' || fieldArray[j] == 'pers_message' ) {
				  innerHTML += "<input type=\"hidden\" name=\"form[recipient_array]["+i+"]["+field+"]\" value =\"" + eval("__change_quote( tempRecipient."+field+")") + "\" />\n";
				} else {
				  innerHTML += "<input type=\"hidden\" name=\"form[recipient_array]["+i+"]["+field+"]\" value =\"" + eval("tempRecipient."+field) + "\" />\n";
				}
			}
			innerHTML += "<input type=\"hidden\" name=\"form[recipient_array]["+i+"][delivery_date]\" value=\"" + tempRecipient.delivery_date/1000 + "\" />\n";
			innerHTML += "<input type=\"hidden\" name=\"form[recipient_array]["+i+"][ship_date]\" value=\"" + tempRecipient.ship_date/1000 + "\" />\n";

			for( var f=0; f < num_flavor_groups; f++ ) {
				flavType = product_items[currentItem]['types'][f];
				innerHTML +=  "<input type=\"hidden\" name=\"form[recipient_array]["+i+"][flavors]["+f+"][flavor]\" value=\"" + tempRecipient.flavors[ f ]['flavor_code'] + "\" />\n";
				innerHTML +=  "<input type=\"hidden\" name=\"form[recipient_array]["+i+"][flavors]["+f+"][type]\" value=\"" + product_items[currentItem]['flavor_group'][f]['flavor_type_idx'] + "\" />\n";
				mycustomFlavor = tempRecipient.flavors[f]['custom_flavor']?tempRecipient.flavors[f]['custom_flavor']:'0'
				innerHTML += tempString =  "<input type=\"hidden\" name=\"form[recipient_array]["+i+"][flavors]["+f+"][custom]\" value=\"" + mycustomFlavor + "\" />\n";
				//alert (tempString);
			}

			innerHTML += "<input type=\"hidden\" name=\"form[recipient_array]["+i+"][lineitem_idx]\" value=\"" + tempRecipient.lineitem_idx + "\" />\n";
			innerHTML += "<input type=\"hidden\" name=\"form[recipient_array]["+i+"][recipient_id]\" value=\"" + tempRecipient.recipient_id + "\" />\n";
			innerHTML += "<input type=\"hidden\" name=\"form[recipient_array]["+i+"][special]\" value=\"" + tempRecipient.special + "\" />\n";
			innerHTML += "<input type=\"hidden\" name=\"form[recipient_array]["+i+"][messageCheck]\" value=\"" + tempRecipient.messageCheck + "\" />\n";
			innerHTML += "<input type=\"hidden\" name=\"form[recipient_array]["+i+"][currentTime]\" value=\"" + currentTime + "\" />\n";
			if(edit_mode){
				innerHTML += "<input type=\"hidden\" name=\"form[recipient_array]["+i+"][edit_mode]\" value=\"1\" />\n";
			}
			if(tempRecipient.has_greeting_card){
				innerHTML += "<input type=\"hidden\" name=\"form[recipient_array]["+i+"][custom_greeting_card]\" value=\""+tempRecipient.custom_greeting_card_token+"\" />\n";
			}
			if(tempRecipient.fouryoursoul_completed){
				innerHTML += "<input type=\"hidden\" name=\"form[recipient_array]["+i+"][fouryoursoul]\" value=\""+tempRecipient.fouryoursoul_completed+"\" />\n";
			}
		}
		innerHTML += "<input type=\"hidden\" name=\"form[offset]\" value=\""+offset/1000+"\" />\n"
		formDataDiv.innerHTML = innerHTML;
	}

	function __change_quote( str ) {
		return str.replace( /\"/g, "&quot;" );
	}

	function __is_form_blank( ){
		var retval = true;
		var tempForm = document.forms['Product'].elements;
		var tempFieldArray = fieldArray.slice(0,fieldArray.length-1);
		var field = '';
		for(var i=0; i < tempFieldArray.length; i++){
			field  = tempFieldArray[i];
			if(field != 'rec_qty' && field != 'shipping_method' && field != 'delivery_date' && field != 'gift_message'){
				eval("if(tempForm['form["+field+"]'].value)retval = false;");
			}
			if (!retval)break;
		}
		return retval;
	}

	function __updateRecipient(){

		var field = '';
		var tempField = null;
		var tempVal = '';
		for(var i=0; i < fieldArray.length; i++){
			field  = fieldArray[i];
			if(field != 'shipping_method' && field != 'delivery_date'){
				if(eval("document.forms['Product']['form["+field+"]']")){
					eval("this."+field+" = eval(\"document.forms['Product']['form[\"+field+\"]'].value\");");
				}
			}
		}
		this.messageCheck = messageCheckVal;
	}

	function __updateRecipientDelivery(){
		this.delivery_date = deliveryDate.getTime();
		this.shipping_method = ship_method;
		this.ship_date = shippingDate;
	}

	function ShowRecipientFlavor(){
		setRecipientFlavors( currentItem );
	}

	var view_flavors = false;

	function setRecipientFlavors( item_idx) {

		if(!has_flavors)
			return;

		has_flavors = false;
		currentItem = item_idx;

		// is this a tin selection type product? if so the edit flavors needs to go to the product tab.
		if( product_items[ currentItem ]['flavor_display'] == 2 || product_items[ currentItem ]['flavor_display'] == 3 ) {
			activate( 'product' );
			return;
		}

		//  Initialize the flavor selection box blocks.
		var recip_flavors = document.getElementById( "recip_flavors" );
		var recip_page_data = document.getElementById( "recip_page_data" );

		var opts = new Array();
		var groupInfo = new Array();
		var sBox = new Array();
		var displayName;
		var nameDiv;
		var firstLine;
		var errorHolder;
		var daDiv = new Array();
		var flavorDiv = document.getElementById('recip_flavors');

		if(!flavorDiv)
			return;
		flavorDiv.innerHTML = '';
		/*
			there aren't any flavors to show.
		*/
		if( !item_idx || !(product_items[item_idx]['flavor_group'].length > 0) )
			return;

		var groupIndex = 0;

		if( !product_items[item_idx]['flavor_group'] ){
			return;
		}

		// find, populate and show a div for a flavor type
		num_flavor_groups = product_items[item_idx]['flavor_group'].length;
		while( groupIndex < num_flavor_groups ) {

			if( product_items[item_idx]['flavor_group'][groupIndex]['allow_only_default'] == '1' ) {
				flavor_html += '<input type="hidden" name="form[flavor_type'+ groupIndex +']" id="type'+ groupIndex +'_flavors" value="" />';
				groupIndex++;
				continue;
			}

			group = flavor_groups[product_items[item_idx]['flavor_group'][groupIndex]['flavor_group_idx']];
			var flavor_html = '';
			has_flavors = true;

			// skip flavors if we have to force custom
			if( product_items[item_idx]['flavor_group'][groupIndex]['only_custom_flavors'] != '1' || product_items[item_idx ]['flavor_display'] != 3 ) {
				var selected = '';
				var checked = '';
				var editCurrentFlavor;
				if(currentRecipient)
					editCurrentFlavor = currentRecipient.flavors[ groupIndex ]['flavor_code'];

				if( editCurrentFlavor == 'CU' ) {

					var customString = currentRecipient.flavors[ groupIndex ]['custom_flavor'];
					if( customString.length > 3 ) {
						var editCustomFlavors = customString.split("|");
						for(j=0; j < editCustomFlavors.length; j++ ) {
							var tmp = editCustomFlavors[j].split("*");
							editCustomFlavors[j] = tmp[0];
						}
					}
				}


				for(var i=0; i< group['flavors'].length; ++i) {

					// is it selected?
					selected = '';
					checked = '';
					if( editCurrentFlavor == 'CU') {
						for(var j=0; j<editCustomFlavors.length;j++) {
							if( editCustomFlavors[j] == group['flavors'][i]['code'] ) {
								selected = ' selected';
								checked = ' checked="checked"';
							}
						}
					} else if( group['flavors'][i]['code'] == editCurrentFlavor ) {
						selected = ' selected';
						checked = ' checked="checked"';
					}

				  var flavor_temp = '';
				  flavor_temp = flavor_detail_template.replace(/%code%/g,group['flavors'][i]['code']);
				  flavor_temp = flavor_temp.replace(/%selected%/g,selected);
				  flavor_temp = flavor_temp.replace(/%checked%/g,checked);
				  flavor_temp = flavor_temp.replace(/%name%/g,group['flavors'][i]['name']);
				  flavor_temp = flavor_temp.replace(/%counter%/g,i);
				  flavor_temp = flavor_temp.replace(/%img%/g,group['flavors'][i]['img']);
				  flavor_temp = flavor_temp.replace(/%idx%/g,groupIndex);
				  flavor_temp = flavor_temp.replace(/%recip%/g,'recip_');

				  if( product_items[item_idx ]['flavor_display'] == 3 ) {
						flavor_temp = flavor_temp.replace(/%callback%/g,'toggleFlavorCheckbox');
						flavor_temp = flavor_temp.replace(/%edit%/g,true);
					} else if( product_items[item_idx ]['flavor_display'] == 1 ) {
						flavor_temp = flavor_temp.replace(/%callback%/g,'toggleFlavorRadio');
						flavor_temp = flavor_temp.replace(/%click_id%/g,'9');
						flavor_temp = flavor_temp.replace(/%edit%/g,',true');
						flavor_temp = flavor_temp.replace(/%imageclick%/g,'onclick="toggleFlavorImage('+groupIndex+','+i+',true);"');
						flavor_temp = flavor_temp.replace(/%count%/g,','+i);
					}
					// cleanup any that might not have been used.
					flavor_temp = flavor_temp.replace(/%count%/g,'');
					flavor_temp = flavor_temp.replace(/%edit%/g,'');
					flavor_temp = flavor_temp.replace(/%imageclick%/g,'');
				  flavor_html += flavor_temp + '\n';
				}
				// if needed, add the custom flavors option to the end of the list. (unless it is checkboxes:3)
				if( product_items[item_idx ]['flavor_display'] != 3 ) {
					if( product_items[item_idx]['flavor_group'][groupIndex]['allow_custom_flavors'] == '1' ) {
						flavor_temp = flavor_detail_template.replace(/%code%/g,'CU');
						flavor_temp = flavor_temp.replace(/%name%/g,'Custom Selection');
						flavor_html += flavor_temp;

					}
				}

			// only custom flavors
			} else {

				// add a form var for this type
				custom_flavor[groupIndex] = true;
				if( product_items[item_idx ]['flavor_display'] == 3 ) {
					flavor_html += '<input type="hidden" name="form[flavor_type'+ groupIndex +']" id="recip_type'+ groupIndex +'_flavors" value="CU" />';
				}
			}

			var group_temp = '';
			group_temp = flavor_main_template.replace(/%label%/g,group['label']);
			if( product_items[item_idx ]['flavor_display'] != 1 ) {
				group_temp = group_temp.replace(/%callback%/g,'SetRecipFlavorSelection');
			}
			group_temp = group_temp.replace(/%click_id%/g,'9');
			group_temp = group_temp.replace(/%recip%/g,'recip_');

			group_temp = group_temp.replace(/%idx%/g,groupIndex);
			group_temp = group_temp.replace(/%error_msg%/g,group['error_msg']);
			group_temp = group_temp.replace(/%first_line%/g,group['first_line']);
			group_temp = group_temp.replace(/%flavors%/g,flavor_html);
			flavorDiv.innerHTML += group_temp;
			groupIndex++;
		}
		recip_flavors.style.display = "block";
		recip_page_data.style.display = "none";

		view_flavors = true;
		return;
	}

	function closeFlavorDiv() {
		tempDiv = document.getElementById('recip_flavors'); tempDiv.style.display='none'
		tempDiv2 = document.getElementById('recip_page_data'); tempDiv2.style.display='block'
		view_flavors = false;
	}

	function persMsgName( form_name ) {
		if( currentItem && product_items[currentItem]['pers_messages'] == 1  && document.forms[ form_name ].elements[ 'form[fname]' ].value != "" ) {
			//document.getElementById( 'deco_fname' ).innerHTML = "for " + document.forms[ form_name ].elements[ 'form[fname]' ].value;
		}
	}

	var specials_tracker = 0;
	function togleSpecial( id ) {
		for( var i=0; i < add_ons.length; i++ ) {
			var sel = document.getElementById( 'sel_special_' + add_ons[ i ] );
			if( sel ) sel.checked = false;
	}
		var slct = document.getElementById( 'sel_special_' + id );
		if( slct ) slct.checked = true;
		specials_tracker = id;
	}//  END

	function clickSpecial( id, color, title ) {
		for( var i=0; i < add_ons.length; i++ ) {
			var spec = document.getElementById( "add_on_caption_" + add_ons[i] );
		if( spec ) spec.style.backgroundColor = "#FFFFFF";
		}
	var bc = document.getElementById( "add_on_caption_" + id );
		if( bc ) bc.style.backgroundColor = "#" + color;
		specials_tracker = id;

	var sel = document.getElementById( 'special_selected' );
	if( sel && title ) sel.innerHTML = title;
	}

	function SaveSpecial(){
		var allDiv = document.getElementById( 'specials_sel_all' );
		if(!allDiv) {
			return;
		}
		currentRecipient.special = '' + specials_tracker;
		if(allDiv.checked){
			default_special = specials_tracker;
			show_special = false;
		}
		return;
	}

	function CancelSpecial(show){
		var allDiv = document.getElementById( 'specials_sel_all' );
		togleSpecial(-1);
		if(!show){
			default_special = 0;
			show_special = false;
		}
		return;
	}

	function trapClick( trackId ) {
		if(document.getElementById('clicks') ) {
			document.getElementById('clicks').value += ',' + trackId;
		}
	}

	function acceptUpgrade( item_id, all_items ) {
		document.getElementById('upgrade_data').style.display = 'none';
		document.getElementById('upgradeAccepted').value = 1;
		selectItem( offerUpgradeItemId, all_items);
		offerUpgradeItemId=0;
		check_item('Product');
	}

	function declineUpgrade() {
		offerUpgradeItemId=0;
		document.getElementById('upgrade_data').style.display = 'none';
		check_item('Product');
	}

	function getRecipientsJSON(){
		return JSON.stringify(recipientArray);
	}

	function save_recipients(){
		var theObj = { foo : 'yum' };
		if(!theObj.hasOwnProperty)
			return;
		var url="/gifts/xml.php";
		var data = "currentItem="+currentItem+"&recips="+getRecipientsJSON();
		var form = document.forms[ 'Product' ];
		var myArray = {};
		myArray['qty'] = form[ 'form[qty]' ].value;
		myArray['numRecips'] = form[ 'form[recips]' ].value;
		myArray['base_token'] = base_token;

		for (i = 0; i < num_flavor_groups; ++i) {
			if( form[ 'form[flavor_type'+i+']' ] )
				myArray['type'+i] = form[ 'form[flavor_type'+i+']' ].value;
		}
		data += "&form="+JSON.stringify(myArray);
		perform_xml_request(url, data, save_callback);
	}
	function save_callback(responseText){
		return;
	}

	function selectFlavorOption( id, value ) {
		var box = document.getElementById( id );
		if( box )
			box.value = value;
	}

	function setFlavorCheckbox( value, type ) {
		var maxFlavors = 4;
		var i = 0;
		var tmp;
		while( i < maxFlavors ) {
			tmp = document.forms.Product['form[flavor_type'+ type +']['+i+']'];
			if( tmp && tmp.value == value )
				tmp.checked = true;
			i++;
		}
	}

	function restoreFlavorValue( name, value, type ) {
		var custom = value.split('|');
		if( custom.length > 1 ) {
			for(var i=0; i < custom; i++ ) {
				var parts = custom[i].split('*');
				if( parts.length > 1 ) {
					setFlavorCheckbox( parts[0], type );
				}
			}
			// disable checkboxes
			toggleFlavorCheckbox( type, false );
			return;
		}

		var ele = document.forms.Product[name];
		if(!ele)
			return;

		if(ele.type == 'select-one' && ele.length > 0 ) {
			for(var i=0; i<ele.length; i++) {
				if( ele.options[i].value == value ) {
					ele.selectedIndex = i;
					ele.value = value;
					break;
				}
			}
		} else if ( ele.type == 'undefined' &&  ele.length > 0 ) {
			var radio;
			for(var i=0; i < ele.length ; i++) {
				if( ele[i].value == value ) {
					ele[i].checked = true;
				} else {
					ele[i].checked = false;
				}
			}
			ele.value = value;
		} else {
			ele.value = value;
		}
		flavor = value;
	}

	function restoreSentiment( value ) {
		var ele = document.forms.Product['form[sentiment]'];
		if(!ele)
			return;
		if(ele.type == 'select-one' && ele.length > 0 ) {
			for(var i=0; i<ele.length; i++) {
				if( ele.options[i].value == value ) {
					ele.selectedIndex = i;
					ele.value = value;
					break;
				}
			}
		} else if ( ele.type == 'undefined' &&  ele.length > 0 ) {
			var radio;
			for(var i=0; i < ele.length ; i++) {
				if( ele[i].value == value ) {
					ele[i].checked = true;
				} else {
					ele[i].checked = false;
				}
			}
			ele.value = value;
		} else {
			ele.value = value;
		}
		document.forms.Product['form[sentiment]'].value = value;
	}

	function clickNameNotBox( type, boxNum, edit ) {
		var extraName;
		if( edit )
			extraName = 'recip_';
		else
			extraName = '';
		var box = document.forms.Product[extraName+'form[flavor_type'+type+']['+boxNum+']'];
		if(box && !box.disabled ) {
			box.checked = !box.checked;
			toggleFlavorCheckbox( type, edit );
		}
	}

	function toggleFlavorImage( type, count, edit ) {

		if( edit )
			edit = 'recip_';
		else
			edit = '';
		var ele;
		var name = edit+'form[flavor_type'+type +']';
		ele = document.forms.Product[name];
		var i = 0;
		// check/uncheck the options
		while(i< ele.length) {
			if( i == count )
				ele[i].checked = true;
			else
				ele[i].checked = false;
			i++;
		}
		toggleFlavorRadio( type, count, edit );
	}

	// sets the value, adds the border.
	function toggleFlavorRadio( type, count, edit ) {
		var border;
		var ele;
		var extraName = '';
		if( edit )
			extraName = 'recip_';

		ele = document.forms.Product[''+extraName+'form[flavor_type'+type+']'];
		var i = 0;
		while(i< ele.length) {
			border = document.getElementById('flavor_box_'+type+'_'+i);
			if( border ) {
				if( ele[i].checked == true ) {
					border.style.border = "1px solid #920000";
					flavor = ele[i].value;
				} else {
					border.style.border = "1px solid #FFFFFF";
				}
			}
			i++;
		}

		document.forms.Product['form[flavor_type'+ type +']'].value = flavor;
		defaultFlavors[ type ] = '0:' + flavor;
		for(var i=0; i < recipientArray.length; i++) {
		 	recipientArray[i].flavors[type]['flavor_code'] = '0:' + flavor;
	 	}

	}

	function toggleFlavorCheckbox( type, edit ) {

		var numFlavors = 4;
		var box;
		var status
		var val;
		var flavorString = '';
		if( edit )
			edit = 'recip_';
		else
			edit = '';

		checkboxCount = 0;

		// go through all the boxes, build a flavor string
		for(var i=0; i < numFlavors; i++) {
			box = document.forms.Product[''+edit+'form[flavor_type'+type+']['+i+']'];
			if( !box )
				continue;
			status = box.checked;
			val = box.value;
			if(status) {
				if( checkboxCount > 0 ) {
					flavorString += '|'+val+'*1';
				} else {
					flavorString += val +'*1';
				}
				checkboxCount++;
			}
			box.disabled = false;
		}

		// if they finished, set the value in the form.
		if( checkboxCount == checkboxMax && checkboxCount ) {

			flavor = flavorString;
			custom_flavor[type] = true;
			document.forms.Product['form[flavor_type'+ type +']'].value = 'CU';
			document.forms.Product['form[custom_flavor]'].value = flavorString;
			defaultFlavors[type] = flavorString;

			for(var i=0; i< recipientArray.length; i++) {
		 		recipientArray[i].flavors[type]['flavor_code'] = 'CU';
		 		recipientArray[i].flavors[type]['custom_flavor'] = flavorString;
	 		}

			// disable any box that isn't used.
			for(var i=0; i < numFlavors; i++) {
				box = document.forms.Product[edit+'form[flavor_type'+type+']['+i+']'];
				status = box.checked;
				if(!status) {
					box.disabled = true;
				}
			}

		// they might have removed a flavor, so clear the string from the form.
		} else {
			flavor = '';
			defaultFlavors[type] = '';
			if( document.forms.Product && document.forms.Product['form[flavor_type'+ type +']'] )
				document.forms.Product['form[flavor_type'+ type +']'].value = '';
		}
	}

	function clickSentimentImage( count ) {
		var ele;
		ele = document.forms.Product['form[sentiment]'];
		if( !ele )
			return;

		var i = 0;
		// check/uncheck the options
		while(i< ele.length) {
			border = document.getElementById( 'sentiment_image_' + i );
			var swapImage = document.getElementById( "gift_image" );
			if( i == count ) {
				ele[i].checked = true;
				ele.value = ele[i].value;
				if( border )
					border.style.border = "1px solid #920000";
				if( swapImage.src ) {
					var img = new Image(250,250);
					img.src = eval( "ImageSentimentSrc_" + i );
					if( img.src )
						swapImage.src = img.src;
				}
			} else {
				ele[i].checked = false;
				if( border )
					border.style.border = "1px solid #FFFFFF";
			}
			i++;
		}
	}

	function cancel_greeting_card( token ) {
		hide_greeting_card_layers();
		for(var i=0; i < recipientArray.length; i++){
		  tempRecipient = recipientArray[i];
		  if(tempRecipient.custom_greeting_card_token && (tempRecipient.custom_greeting_card_token == token)){
				tempRecipient.has_greeting_card = 0;
				tempRecipient.messageCheck = 1;
				greeting_card( 'Product', 'form[gm_standard]' );
				display_greeting_card();
		  }
		}
	}


	function add_rem_item( lineitem_id ) {
		lineitem_idx = lineitem_id;
		var extra;
		var qty_box;
		var qty_box_total;
		var clusions = '';
		var checkbox = document.getElementById('lineitem_' + lineitem_id );
		if( !checkbox ) {
			return false;
		}

		// what product is this?
		var item_idx = document.getElementById('item_idx_' + lineitem_id ).value;

		if( !item_idx > 0 ) {
			alert('missing item_idx');
			return false;
		}

		// set vars for calendar
		currentItem = item_idx;
		product_idx = items[item_idx];
		maxTransitDays = product_items[item_idx]['max_transit_days'];
		if( maxTransitDays == '' || maxTransitDays < 1 ) {
			maxTransitDays = 5;
		}
		leadTime = product_items[item_idx]['leadTime'];
		item_cost = product_items[item_idx]['item_costs'];
		clusions = document.getElementById( 'lineitems['+ lineitem_id +'][clusions]' );
		qty_box = document.getElementById('qty_' + lineitem_id );
		qty_box_total = document.getElementById('qty_' + lineitem_id +'_total');

		// this item they just checked can't have a greeting card and they have one for this recip.
		if( !check_custom_card_option() ) {
			alert('A personalized greeting card can\'t be included with this item '); //\'
			if (checkbox.type == 'checkbox') {
				checkbox.checked = false;
			} else {
				checkbox.value = 0;
			}
		}

		var existing_index = selected_lineitems.indexOf(lineitem_id);
		// an item is selected.
		if (((checkbox.type == 'checkbox') && checkbox.checked)
				|| ((checkbox.type != 'checkbox') && checkbox.value)) {

			//add to the list of selected line items
			if (existing_index == -1) {
				selected_lineitems.push(lineitem_id);
			}

			var i = 0;
			// hide or show item options
			while( i < lineitems.length ) {

				// the div with the item options (expand/collapse part)
				extra = document.getElementById('extra_' + lineitems[i] );
				qty_box = document.getElementById('qty_' + lineitems[i] );
				qty_box_total = document.getElementById('qty_' + lineitems[i] +'_total');
				checkbox = document.getElementById('lineitem_'+lineitems[i] );

				if( !checkbox ) {
					i++;
					continue;
				}

				if (((checkbox.type == 'checkbox') && checkbox.checked)
						|| ((checkbox.type != 'checkbox') && checkbox.value)) {
					if (qty_box) {
						qty_box.disabled = false;
						if( !qty_box.value || qty_box < 1 )
							qty_box.value = 1;
					}
					if (qty_box_total) {
						qty_box_total.disabled = false;
						if (!qty_box_total.value || qty_box_total < 1 )
							qty_box_total.value = 1;
					}

				} else {
					if (qty_box) {
						qty_box.disabled = true;
					}
					if (qty_box_total) {
						qty_box_total.disabled = true;
					}
				}

				// this is the item to activate
				if( lineitems[i] == lineitem_id ) {
					extra.style.display = 'block';
					var tmp = edit_delivery_dates[lineitem_id] / 1000;
					if(tmp > 0 ) {
						currentDate = tmp;
					}
					GetCalendarLineitem( lineitem_idx);

				// hide the options for this item, it isn't the active one.
				} else {
					extra.style.display = 'none';
				}
				i++;
			} // while items

		} else {

			//take it out if it is no longer selected
			if (existing_index != -1) {
				selected_lineitems.splice(existing_index, 1);
			}

			extra = document.getElementById('extra_' + lineitem_id );
			extra.style.display = 'none';
			checkbox = document.getElementById('lineitem_'+ lineitem_id );
			if( qty_box )
				qty_box.disabled = true;
			if( qty_box_total )
				qty_box_total.disabled = true;
		}



	}//  end

	var qty_err_found = false;
	function check_item_qty( field, button ) {
		var fld = document.getElementById( field );
		if( fld ) {
			if( fld.value.length > 0 ) {

				//  Make sure that this field has ONLY numeric valus.
				var regex = /^[0-9]*$/g

				if( qty_err_found == false && regex.test( fld.value ) == false ) {
					alert( "The quantity field can only contain numeric values." );
					qty_err_found = true;
				}
			}
		}
	}

	function trim(sString) {
		while (sString.substring(0,1) == ' ') {
			sString = sString.substring(1, sString.length);
		}
		while (sString.substring(sString.length-1, sString.length) == ' ') {
			sString = sString.substring(0,sString.length-1);
		}
		return sString;
	}

	function checkShipToState( el ) {

		var state = null;
		if( el && el.selectedIndex ) {
			state = el.options[ el.selectedIndex ].value;
		}
		if( !state )
			return;

		// check each item, can it go to akhi?
		var i = 0;
		while( i < lineitems.length ) {
			akhi_status = 1;
			if( state == "AK" || state == "HI" ) {
				akhi_status = document.getElementById('akhi_' + lineitems[i] ).value;
			} else {
				akhi_status = 1;
			}
			able_item( lineitems[i], akhi_status );
			i++;
		}

		// the month needs to be redrawn if they change states (or shipping recalculated)
		if( currentItem && lineitem_idx ) {
			//summaryDiv.innerHTML = '';
			currentDate = '';
			GetCalendarLineitem( lineitem_idx);

			//UpdateSummary();

		}
	}

	function checkShipZip() {

	}

	function able_item( lineitem, enable ) {
		var check = document.getElementById('lineitem_'+ lineitem );
		var msg = document.getElementById('akhi_msg_'+ lineitem );
		var extra = document.getElementById('extra_' + lineitem );

		if( !check )
			return;

		if( enable > 0 ) {
			check.disabled = false;
			if( msg )
				msg.style.display = 'none';
		} else {
			// needs to show some message telling that this item can't ship to AK/HI
			check.checked = false;
			check.disabled = true;
			extra.style.display = 'none';
			if( msg )
				msg.style.display = 'block';

			// the lineitem isn't active anymore...
			if( lineitem_idx == lineitem ) {
				lineitem_idx = null;
				currentItem = null;
			}

		}

	}

	function check_custom_card_option() {

		var opt = document.getElementById('gc_option');
		if( opt && opt.style.display == 'none' ) {
			opt.style.display = 'block';
		}

		// did we offer a card?
		var custom_btn = document.getElementById('message_type_custom');
		if( !custom_btn ) {
			return true;
		}

		// it is a custom card, are there items that can't have one?
		var ok = true;
		var i = 0;
		while( i < lineitems.length ) {
			var not_allow = document.getElementById('lineitems[' + lineitems[i] +'][no_greeting_cards]' );
			if( not_allow.value == 1 ) {

				// if the product is checked we have a problem
				var checkbox = document.getElementById('lineitem_' + lineitems[i]);
				if ( checkbox && checkbox.checked) {
					ok = false;
				}
			}
			i++;
		}

		// if not checked, there can't be a problem now, but we can remove the option.
		if(!custom_btn.checked) {
			if( !ok ) {
				var div = document.getElementById('gc_option');
				if( div )
					div.style.display = 'none';
			}
			ok = true;
		}

		return ok;
	}

	function check_products_for_card() {

		check_custom_card_option();

		var custom_btn = document.getElementById('message_type_custom');
		if( custom_btn ) {
			//UpdateSummary();
		}

	}

	function google_checkout_post( form_name ) {

		var el = document.getElementById( 'go_google_checkout' );
		if( el ) { el.value = 1; }

		document.forms[ 'Product' ].submit();
	}

	function recipient_lister( count ) {
		var el = document.getElementById( 'recipient_counter_recips' );

		if( !el || count <= 0 ) {
			return;
		}

		//  Hide all currently displayed items.
		var recips = getElementsByStyleClass( 'recipient_line' );

		if( recips && recips.length > 0 ) {
			for( var i = 0; i < recips.length; i++ ) {
				recips[i].style.display = "none";
			}
		}

		for( var i = 1; i <= 20; i++ ) {
			var td = document.getElementById( "recipient_list_" + i );
			if( td ) {
				if( i <= count ) {
					td.style.display = "block";
				}
			}
		}

		//  Adjust the Google Checkout option, if necessary.
		if( count == 1 && google_checkout_cant == false ) {
			$("#google_checkout_enabled").css( "display", "block" );
			$("#google_checkout_disabled").css( "display", "none" );
		} else if( count > 1 || google_checkout_cant == true ) {
			$("#google_checkout_enabled").css( "display", "none" );
			$("#google_checkout_disabled").css( "display", "block" );
		} else {}
	}

	function useExistingRecip( element, num ) {

		//  Get the data fields.
		var name_holder = document.getElementById( "recip_name_" + num );

		//  RESET THE DATA
		if (name_holder && !element.selectedIndex) {
			//  Reset the data values.
			name_holder.value = "";
			name_holder.disabled = false;
			name_holder.style.background = "white";

		} else {
		//  USE PREVIOUS RECIPIENT

			//  Adjust the name field.
			if (name_holder) {
				name_holder.value = "";
				name_holder.disabled = true;
				name_holder.style.background = "#dddddd";
			}

		}
	}

	function showCorpListInstructions() {
		var el = document.getElementById( 'corporate_list_bubble' );
		if( el ) { el.style.display = "block"; }
	}

	function hideCorpListInstructions() {
		var el = document.getElementById( 'corporate_list_bubble' );
		if( el ) { el.style.display = "none"; }
	}

    function swap_details( name ) {

		//Hide all necessary information.
		$(".item_x_info").css( "display", "none" );
		$(".item_x_title").css( "background", "#ffffff" );
		$(".item_x_title").css( "borderBottom", "1px solid #6e594d" );

		//  Highlight the necessary information.
		$("#item_x_" + name + "_info").css( "display", "block" );
		$("#item_x_" + name).css( "backgroundColor", "#ebece1" );
		$("#item_x_" + name).css( "borderBottom", "1px solid #ebece1" );
	}

