/* some functions for the personalization interface */

/* Personalization class and methods: */
function pers_util(group_id) {
	this.groupId = group_id;
	
	var checkbox = inputFinder('checkbox', this.groupId);
	this.checkbox = checkbox[0];
	
	this.isActive = function () { if (this.checkbox.checked == true) return true; else return false; }
	this.activate = function () { if (!this.isActive()) { this.checkbox.click(); this.focusFirst(); } }
	this.deactivate = function () { if (this.isActive()) this.checkbox.click(); }
	this.focusFirst = function () { this.allLines[0].focus(); }
	
	this.selectedProduct = checkProducts;
	this.validateLines = checkLines;
	
	this.selectedLines = function () { if (this.selectedProduct() == 'none') return false; else return inputFinder('text', this.groupId, this.selectedProduct()); }
	this.unSelectedLines = function() {
		if (this.selectedLines() == 'none') return 'none';
		var matches = new Array();
		for (var t=0; t < this.allLines.length; t++) {
			if (this.allLines[t].getAttribute('persGroupProd') != this.selectedProduct()) matches.push(this.allLines[t]);
		}
		return matches;
	}
	this.allLines = inputFinder('text',this.groupId);
	
	this.reset = resetGroup;
	this.clearUnselected = clearUnselect;
	
	this.prodName = getProdName;
	this.prodPrice = getProdPrice;
}

/* Returns the selected option when a radio group exists, or returns 0 if no radios exist. */
function checkProducts() {
	var products = inputFinder('radio', this.groupId);
	if (products.length == 0) return 0;
	else {
		for (var i=0; i < products.length; i++) {
			if (products[i].checked == true) return products[i].getAttribute('persGroupProd');
		}
	}
	return 'none';
}

/* Validates the selected lines. */
function checkLines() {
	if (this.selectedProduct() == 'none') return false;
	var lines = inputFinder('text', this.groupId, this.selectedProduct());
	var blankCounter = 0;
	for (var i=0; i < lines.length; i++) {
		if (lines[i].value == "") blankCounter += 1;
	}
	if (blankCounter == lines.length) return 'empty';
	else if (blankCounter == 0) return 'ready';
	else return 'partial';
}

/* Loops through the lines, resets their images, input values, and resets the character counter */
function resetGroup() {
	for (var x=0; x < this.allLines.length; x++) {
		var cur_group = new input_util(this.allLines[x]);
		cur_group.resetImg();
		cur_group.field.value = '';
		cur_group.updateCount();
	}
}

/* Clears unselected radio groups when a new one is selected. */
function clearUnselect() {
	if (this.unSelectedLines() == 'none') return false;
	for (var y=0; y < this.unSelectedLines().length; y++) {
		var cur_unselect = new input_util(this.unSelectedLines()[y]);
		cur_unselect.field.value = '';
		cur_unselect.resetImg();
		cur_unselect.updateCount();
	}
}

/* Gets selected product price from input attribute */
function getProdPrice() {
	if (this.selectedProduct() == 'none') return false;
	if (this.checkbox.getAttribute('prodPrice') != null) return this.checkbox.getAttribute('prodPrice');
	else {
		return inputFinder('radio', this.groupId, this.selectedProduct())[0].getAttribute('prodPrice');
	}
}

/* Gets selected product name from input attribute */
function getProdName() {
	if (this.selectedProduct() == 'none') return false;
	if (this.checkbox.getAttribute('prodName') != null) return this.checkbox.getAttribute('prodName');
	else {
		return inputFinder('radio', this.groupId, this.selectedProduct())[0].getAttribute('prodName');
	}
}

/* </pers class/methods> */

/* Input control class/methods */
function input_util(mod_input) {
	this.field = mod_input;
	
	this.groupId = this.field.getAttribute('persGroup');
	this.prodId = this.field.getAttribute('persGroupProd');
	this.line = this.field.getAttribute('persGroupProdLine');
	this.piid = this.field.getAttribute('piid');
	this.maxLen = this.field.getAttribute('maxlength');
	this.remainCounter = document.getElementById('remain_'+this.groupId+this.prodId+this.line);
	this.img = document.getElementById('pers_img_'+this.field.getAttribute('imgKey'));
	this.uppercaseFlag = this.field.getAttribute('uppercase');
	
	this.imgUrl = urlExtract;
	this.updateTimer = keyTimer;
	this.updateImg = imgUpdate;
	this.resetImg = function () { this.img.src = this.imgUrl() + '?product_item_id=' + this.piid; }
		
	this.siblings = siblingLookup;
	this.siblingStatus = siblingValues;
	
	this.select = function () { checkGroup(this.groupId, true); checkGroupProd(this.groupId, this.prodId, true); }
	this.unSelect = function () { checkGroup(this.groupId, false); checkGroupProd(this.groupId, this.prodId, false); }
		
	this.curLen = function () { return this.field.value.length; }
	this.keyTrigger = function () {
		if (this.uppercaseFlag == 'true') this.toUppercase();
		this.updateCount();
	}
	this.updateCount = function () { this.remainCounter.innerHTML = (this.maxLen - this.field.value.length); };
	this.toUppercase = function () { this.field.value = this.field.value.toUpperCase(); }
	
	this.clearOthers = function() { var clearer = new pers_util(this.groupId); clearer.clearUnselected(); }
}

/* Returns url of image, minus query string. */
function urlExtract() {
	var img_src = this.img.src;
	img_src = img_src.split('?');
	
	return img_src[0];
}

/* starts the keystroke clock, voiding any that are already in progress. */
function keyTimer() {
	if (typeof ticking_down != 'undefined') {
		if (ticking_down == true) {
			clearTimeout(key_clock);
		}		
	}
	ticking_down = true;
	key_clock = setTimeout('current_input.updateImg()',500);
}

/*
	Loops through lines in a product builds a query string to be appended to the product image src,
	which triggers a new image request from the browser to the server.
*/
function imgUpdate() {
	ticking_down = false;
	var queryString = '?product_item_id='+this.piid;
	if (this.field.value.length > 0) queryString += '&line['+this.line+']='+encodeURIComponent(this.field.value);
	for (var c=0; c < this.siblings().length; c++) {
		if (this.siblings()[c].value.length > 0 && this.siblings()[c].getAttribute('imgKey') == this.field.getAttribute('imgKey')) {
			queryString += '&line['+this.siblings()[c].getAttribute('persGroupProdLine')+']='+escape(this.siblings()[c].value);
		}
	}

	this.img.src = this.imgUrl() + queryString;
}

/* Loops through siblings of the focused input and validates them. */
function siblingValues() {
	var blankCounter = 0;
	for (p=0; p < this.siblings().length; p++) {
		if (this.siblings()[p].value == "") blankCounter = blankCounter +1;
	}
	if (this.siblings().length == 0) return 'none';
	else if (blankCounter == this.siblings().length) return 'empty';
	else if (blankCounter == 0) return 'ready';
	else return 'partial';
}

/* Finds siblings to the focused field. */
function siblingLookup() {
	var inputs = document.getElementsByTagName('input');
	var siblingList = new Array();
	var imgKey = this.field.getAttribute('imgKey');
	for (i=0; i < inputs.length; i++) {
		var cur_input = inputs[i];
		if (
			cur_input.getAttribute('persGroup') == this.groupId && 
			cur_input.getAttribute('persGroupProd') == this.prodId &&
			cur_input.getAttribute('persGroupProdLine') != this.line &&
			//cur_input.getAttribute('imgKey') == imgKey &&
			cur_input.getAttribute('type') == 'text'
		) {
			siblingList.push(cur_input);
		}		
	}
	return siblingList;
}

/* </input class/methods> */


/* button class/methods */

/* class that creates new buttons and allows basic manipulation of their attributes. */
function button(id) {
	var new_button = document.createElement('input');
	new_button.setAttribute('type','image');
	new_button.style.marginLeft = '10px';
	if (typeof id != 'undefined') new_button.setAttribute('id', id);
	
	this.obj = new_button;
	//this.id = function (id) { this.obj.setAttribute('id',id); }
	this.src = function (addr) { this.obj.setAttribute('src',addr); }
	//this.click = function (stmt) { this.obj.onclick = function () { stmt; } }
	
	this.float = function (loc) { /* this.obj.style.cssFloat = loc; */ return; }

	this.disable = function () { this.obj.disabled = true; }
	this.enable = function () { this.obj.disabled = false; }
	
	this.show = function () { this.obj.style.display = 'block'; }
	this.hide = function () { this.obj.style.display = 'none'; }

	this.build = function () {
		if (this.obj.parentNode != document.getElementById('pers_button_nest')) document.getElementById('pers_button_nest').appendChild(this.obj);
	}
	
	this.showing = function () { if (this.obj.style.display != 'none') return true; else return false; }
}


/* Various utilities: */

function arrayDump(an_array) {
	var arrayValues = "";
	for (y in an_array) {
		arrayValues += y+" => "+an_array[y]+"<br>";
	}
	
	var debugWin = window.open('#', 'debug');
	debugWin.document.write(arrayValues);
	//alert(arrayValues)
}

// Array Remove - By John Resig (MIT Licensed)
Array.prototype.remove = function(from, to) {
  var rest = this.slice((to || from) + 1 || this.length);
  this.length = from < 0 ? this.length + from : from;
  return this.push.apply(this, rest);
};

Array.prototype.search = function(search_obj) {
	for (i in this) {
		if (this[i] == search_obj) return i;
	}
	return false;
}

function getElementsByAttribute(attrib, val) {
	var all_elements = document.getElementsByTagName('*');
	var match_list = new Array();
	for (var i=0; i < all_elements.length; i++) {
		if ((all_elements[i].getAttribute(attrib) == val && typeof val != 'undefined') || (all_elements[i].getAttribute(attrib) != null && typeof val == 'undefined')) {
			match_list.push(all_elements[i]);
		}
	}
	return match_list;
}

String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g, '');
}

function submit_form() {
	if (ajax_request()) document.pers.submit();
	else document.AddToCart.submit();
}

function pers_forms_exist() {
	if (document.getElementById('pers_forms').innerHTML != "") return true;
	else return false;
}

function ajax_request() {
	var ajax_req = document.getElementById('0_ajax_request');
	if (ajax_req && ajax_req.value == 'true') return true;
	else return false;
}
function dont_show_top() {
	var dont = document.getElementById('0_dont_show_top');
	if (dont && dont.value == 'true') return true;
	else return false;
}
function force_checkbox() {
	var strict = document.getElementById('0_force_checkbox');
	if (strict && strict.value == 'true') return true;
	else return false;	
}



/*
	This function is set to append the price rows on the p3 page if a bad zip was entered and we are
	sent back to the p3 page from checkout.add.
*/

function addLoadEvent(func) {
	var oldonload = window.onload;
	if (typeof window.onload != 'function') {
		window.onload = func;
	}
	else {
		window.onload = function() {
			if (oldonload) {
				oldonload();
			}
			func();
		}
	}
}

addLoadEvent(rowBuild);
function rowBuild(executeFlag) {
	if (executeFlag != 1) {
		if (document.getElementById('prod_list')) setTimeout('rowBuild(1)', 500);
	}
	else {
		var input_nest = document.getElementById('pers_forms');
		var already_seen = new Array();
		if (input_nest && input_nest.innerHTML != '') {
			var nodeList = input_nest.childNodes;

			for (var i=0; i < nodeList.length; i++) {
				var curNode = nodeList[i];

				/* If element node */
				if (curNode.nodeType == 1 && already_seen.include(curNode.getAttribute('prodName')) == false) {
					already_seen.push(curNode.getAttribute('prodName'));
					append_prod_list(curNode.getAttribute('prodName'), curNode.getAttribute('prodPrice'));
				}
			}
		}
	}
	
}

function get_file_name(url) {
	var url_parts = url.split('/');
	return url_parts[(url_parts.length -1)];
}

function assembleInterface(responseText) {
	var newHolder = document.createElement('div');
	newHolder.setAttribute('id','pers_container');
	newHolder.innerHTML = unescape(responseText);
	
	document.getElementsByTagName('body')[0].appendChild(newHolder);
	
	persInterface("show");
}

function shadeToggle(forcedState) {
	var shaderTest = document.getElementById('0_shader');
	if (shaderTest) {
		document.getElementById('0_shader').parentNode.removeChild(document.getElementById('0_shader'));
		if (forcedState == "show") shadeToggle();

		//ugly hack time
		if ((checkout_page() == 'delivery' || checkout_page() == 'giftcard') && window.navigator.appName == 'Microsoft Internet Explorer') {
			selects_toggle('visible');
		}
		
	}
	else {
		if (forcedState == 'destroy') return;
		var newShade = document.createElement('div');
		newShade.style.width = '100%';

		if (!isNaN(window.scrollMaxY)) newShade.style.height = (window.innerHeight + window.scrollMaxY) + 'px'; //if browser is firefox
		else if (!isNaN(document.height)) newShade.style.height = document.height + 'px'; //if browser is safari
		else if (!isNaN(document.documentElement.scrollHeight)) newShade.style.height = document.documentElement.scrollHeight + 'px'; //if IE

		newShade.style.position = 'absolute';
		newShade.style.left = '0px';
		newShade.style.top = '0px';
		newShade.style.opacity = '.8';
		newShade.style.filter = 'alpha(opacity=80)'; //ie
		newShade.style.background = 'black';
		newShade.setAttribute('id','0_shader');
		newShade.style.zIndex = '400';
		newShade.onclick = function () { persInterface("hide"); }
		
		var parent_node = document.getElementsByTagName('body')[0];
		//var parent_node = document.getElementById('focus');
		parent_node.appendChild(newShade);
		
		//ugly hack time
		if ((checkout_page() == 'delivery' || checkout_page() == 'giftcard') && window.navigator.appName == 'Microsoft Internet Explorer') {
			selects_toggle('hidden');
		}	
	}
}

function inputFinder(type, groupId, prodId, line) {
	var tag_matches = new Array();
	var tag_list = document.getElementsByTagName('input');
	for (i=0; i < tag_list.length; i++) {
		var cur_tag = tag_list[i];
		var checksum = 0;

		if (typeof groupId != 'undefined' && typeof prodId != 'undefined' && typeof line != 'undefined') {
			if (cur_tag.getAttribute('type') == type && cur_tag.getAttribute('persGroup') == groupId && cur_tag.getAttribute('persGroupProd') == prodId && cur_tag.getAttribute('persGroupProdLine') == line) {
				tag_matches.push(cur_tag);
			}
		}
		else if (typeof groupId != 'undefined' && typeof prodId != 'undefined') {
			if (cur_tag.getAttribute('type') == type && cur_tag.getAttribute('persGroup') == groupId && cur_tag.getAttribute('persGroupProd') == prodId) {
				tag_matches.push(cur_tag);
			}		
		}
		else if (typeof groupId != 'undefined') {
			if (cur_tag.getAttribute('type') == type && cur_tag.getAttribute('persGroup') == groupId) {
				tag_matches.push(cur_tag);
			}			
		}
		else return false;
		
	}
	return tag_matches;
}

function commit_pers() {
	delete_pers();
	var commit_issue = false;
	var blank_count = 0;
	
	var pers = pers_list('active');
	for (var i=0; i < pers.length; i++) {
		var cur_group = new pers_util(pers[i].getAttribute('persGroup'));

		var cur_status = cur_group.validateLines();

		if (cur_status == 'ready') {
			if (!ajax_request()) append_prod_list(cur_group.prodName(), cur_group.prodPrice());
			for (z=0; z < cur_group.selectedLines().length; z++) {
				var cur_line = cur_group.selectedLines()[z];
				saveLine('pers['+cur_line.getAttribute('piid')+']['+cur_line.getAttribute('persGroupProdLine')+']',cur_line.value);
			}
		}
		else if (cur_status == 'partial') {
			//commit_issue = true;
			if (!ajax_request()) append_prod_list(cur_group.prodName(), cur_group.prodPrice());
			for (y=0; y < cur_group.selectedLines().length; y++) {
				var cur_line = cur_group.selectedLines()[y];
				saveLine('pers['+cur_line.getAttribute('piid')+']['+cur_line.getAttribute('persGroupProdLine')+']',cur_line.value);
			}
		}
		else if (cur_status == 'empty' || cur_status == false) {
			blank_count++;
		}
		
	}
	
	if (blank_count == pers.length && blank_count > 0) {
		alert('Please fill out the lines for the personalization(s) you have selected.');
		delete_pers();
		return false;
	}
	
	if (commit_issue == true) {
		var confirmPartial = confirm("You haven't filled out all of the available lines for the personalization(s) you selected.  Continue anyway?");
		if (confirmPartial == false) {
			if (!ajax_request()) delete_pers();
			return;
		}
	}
	
	if (ajax_request()) {
		ajax_submit();
	}
	else if (typeof window.forced_pers_interface != 'undefined' && window.forced_pers_interface == true) document.AddToCart.submit();
	else {
		force_close_interface();
		if (window.googletogglebutton && document.getElementById('googlebutton')) googletogglebutton();
	}
}

function saveLine(name, value) {
	var newInput = document.createElement('input');
	newInput.setAttribute('type', 'hidden');
	newInput.setAttribute('name', name);
	newInput.setAttribute('value', value);
	newInput.setAttribute('kind','pers_saved');
	
	document.getElementById('pers_forms').appendChild(newInput);
	
	return newInput;
}

function pers_list(active_flag) {
	var pers = document.getElementsByTagName('input');
	var matches = new Array();
	for (i=0; i < pers.length; i++) {
		if (active_flag == 'active') {
			if (pers[i].getAttribute('type') == 'checkbox' && pers[i].getAttribute('persGroup') != null && pers[i].checked == true) {
				matches.push(pers[i]);
			}
		}
		else {
			if (pers[i].getAttribute('type') == 'checkbox' && pers[i].getAttribute('persGroup') != null) {
				matches.push(pers[i]);
			}		
		}
	}
	return matches;
}

function resetForm() {
	document.pers.reset();
	//close_pers();
	delete_pers();
	var pers = pers_list();

	for (var i=0; i < pers.length; i++) {
		var cur_pers = pers[i];
		var cur_group = new pers_util(cur_pers.getAttribute('persGroup'));
		cur_group.reset();
	}
}

function expand_pers(groupId) {
	if (ajax_request() || dont_show_top()) return false;

	if (isNaN(groupId)) var group_rows = getElementsByAttribute('groupId');
	else var group_rows = getElementsByAttribute('groupId', groupId);
	for (var j=0; j < group_rows.length; j++) {
		var cur_row = group_rows[j];
		if (cur_row.tagName == 'DIV') {
			cur_row.style.display = 'block';
		}
	}
}
function close_pers(groupId) {
	if (ajax_request() || dont_show_top()) return false;
	
	if (isNaN(groupId)) var group_rows = getElementsByAttribute('groupId');
	else var group_rows = getElementsByAttribute('groupId', groupId);
	for (var j=0; j < group_rows.length; j++) {
		var cur_row = group_rows[j];
		if (cur_row.tagName == 'DIV') {
			cur_row.style.display = 'none';
		}
	}	
}

/* fixes return key issue, and disallowed chars */
function persKeyDown(evt) {
	if (evt.keyCode == 13) return false;
	if ((evt.charCode < 32 || evt.charCode > 126) && evt.charCode != 0) return false;
}

function persKey(modded_input) {
	current_input = new input_util(modded_input);

	if (current_input.curLen() > 0) current_input.select();
	
	current_input.keyTrigger();
	current_input.updateTimer();
	current_input.clearOthers();	
}

function persBlur(blur_input) {
	if (typeof ticking_down != 'undefined') {
		if (ticking_down == true) {
			clearTimeout(key_clock);
		}
	}
	var forceUpdate = new input_util(blur_input);
	forceUpdate.updateImg();
}

function onCheckout() {
	if (ajax_request()) return true;
	else return false;
}

function forcedLayout(strictFlag) {
	clear_buttons();
	document.getElementById('0_shader').onclick = '';
	
	if (strictFlag != 'strict') {
		toggle_top('block');
		toggle_pers('block');
		toggle_force_check('none');
		change_top_banner('personalization_hdr_addyours.gif');
		
		var save_continue = new button('commit_button');
		save_continue.src('/global/images/buttons/save_and_continue_grey.gif');
		save_continue.disable();
		save_continue.obj.onclick = function () { metrics_info(5); commit_pers(); return false; }
		
		var no_thanks = new button('cancel_button');
		no_thanks.src('/global/images/buttons/no_thanks.gif');
		no_thanks.obj.onclick = function () { metrics_info(4); document.AddToCart.submit(); return false; }
		
		no_thanks.build();
		save_continue.build();
		
		/* Metrics */
		document.getElementById('pers_close_button').onclick = function () { 
			metrics_info(6);
			document.AddToCart.submit();
		}
	}
	//if strict
	else {
		toggle_top('none');
		toggle_pers('block');
		toggle_force_check('block');
		change_top_banner('personalization_options.gif');
		document.getElementById('pers_close_button').style.display = 'none';
		
		var continue_button = new button('commit_button');
		continue_button.src('/global/images/buttons/save_and_continue_grey.gif');
		continue_button.float('right');
		continue_button.obj.onclick = function () { commit_pers(); return false; }
		continue_button.disable();
		continue_button.build();
	
		document.getElementById('pers_close_button').onclick = function () { document.AddToCart.submit(); }
	}
}

function normalLayout() {
	toggle_top('block');
	toggle_pers('block');
	toggle_force_check('none');
	change_top_banner('personalization_hdr_memorable.gif');
	clear_buttons();

	var no_thanks = new button('cancel_button');
	no_thanks.src('/global/images/buttons/no_thanks.gif');
	no_thanks.obj.onclick = function () { force_close_interface(); return false; }
	
	var personalize = new button('commit_button');
	
	personalize.obj.onclick = function () { commit_pers(); return false; }
	if (!ajax_request() && !pers_forms_exist()) {
		personalize.src('/global/images/buttons/personalize_grey.gif');
		personalize.disable();
	}
	else {
		personalize.src('/global/images/buttons/personalize_button.gif');
	}
	
	no_thanks.build();
	personalize.build();
	
	document.getElementById('0_shader').onclick = function () { persInterface("hide"); }
	
	toggle_force_check('none');
	
	//metrics
	if (!ajax_request()){
		metrics_info(7);
		no_thanks.obj.onclick = function () { metrics_info(8); force_close_interface(); return false; }
		personalize.obj.onclick = function () { metrics_info(9); commit_pers(); return false; }
		document.getElementById('pers_close_button').onclick = function () { metrics_info(10); force_close_interface(); }
	}
	else {
		metrics_info(11);
		no_thanks.obj.onclick = function () { metrics_info(12); force_close_interface(); return false; }
		personalize.obj.onclick = function () { if (!pers_forms_exist()) {metrics_info(13);} commit_pers(); return false; }
		document.getElementById('pers_close_button').onclick = function () { metrics_info(14); force_close_interface(); }
	}
}

function persInterface(forcedAction, forcedFlag) {
	var personalization_interface = document.getElementById('pers_interface');
	if (forcedAction == "show") {
		
		if (forcedFlag == 'true') window.forced_pers_interface = true;
		
		//global variable to tell us the interface has been opened at least once:
		window.pers_interface_shown = true;
		
		window.scrollTo(0,0);
		
		if (forcedFlag == 'true' && pers_forms_exist()) {
			document.AddToCart.submit();
			return;
		}
		
		/* This fixes a browser "issue" where if a customer soft refreshes a page, the form info is still present. */
		if (!pers_forms_exist() && !ajax_request()) resetForm();

		/* Unhappy hack.  Puts the perz interface on the same node level as the shade so that it can show above it.  Damne IE zIndexes. */
		if ((is_ie6() || is_ie7()) && $(personalization_interface).parent().attr('id') == 'focus') {
			$(personalization_interface).appendTo('body');
			//$(personalization_interface).remove();
		}
		
		shadeToggle("show");
		
		if (forcedFlag == 'true' && !force_checkbox()) {
			forcedLayout();
			
			metrics_info(0); //metrics
		}
		else if (forcedFlag == 'true' && force_checkbox()) {
			forcedLayout('strict');
		}
		else {
			normalLayout();
		}
		
		personalization_interface.style.display = 'block';
		
		if (!ajax_request() && !pers_forms_exist() && pers_list().length == 1) {
			var firstLine = new pers_util(0);
			firstLine.activate();
		}
		
	}
	else {
		var groups = pers_list('active');
		for (p=0; p < groups.length; p++) {
			var cur_match = new pers_util(groups[p].getAttribute('persGroup'));
			if ((cur_match.validateLines() == 'partial' || cur_match.validateLines() == 'ready') && cur_match.isActive() == true) {
				var askThem = true;
			}
		}
		if (askThem == true && !ajax_request() && !pers_forms_exist()) {
			var question = confirm("Are you sure you want to cancel? Personalization(s) are not saved.");
			if (question == true) {
				document.getElementById('cancel_button').click();
			}
		}
		else {
			document.getElementById('cancel_button').click();
		}
	
	}
}

function force_close_interface() {
	if (!ajax_request()) {
		document.getElementById('pers_interface').style.display = 'none';
	}
	else {
		document.getElementById('pers_container').parentNode.removeChild(document.getElementById('pers_container'));
	}
	shadeToggle("destroy");
}

function clear_buttons() {
	document.getElementById('pers_button_nest').innerHTML = '';
}

function checkGroup(group_id, state) {
	var input = inputFinder('checkbox', group_id);
	input = input[0];

	input.checked = state;	
	if (state == true) {
		if (!ajax_request() && document.getElementById('pers_force_label') && document.getElementById('pers_force_label').style.display != 'none') {
			document.getElementById('pers_force_checkbox').checked = false;
		}
		enable_commit();
	}
	else {
		if (!ajax_request() && pers_list('active').length == 0) disable_commit();
	}
}

function checkGroupProd(group_id, prod_id, state) {
	var inputs = document.getElementsByTagName('input');
	for (i=0; i < inputs.length; i++) {
		var cur_input = inputs[i];
		if (
				cur_input.getAttribute('type') == 'radio' &&
				cur_input.getAttribute('persGroup') == group_id &&
				cur_input.getAttribute('persGroupProd') == prod_id
			) {
			if (typeof state != 'undefined') {
				cur_input.checked = state;
				checkGroup(group_id, state);
			} 
			else {
				if (cur_input.checked == true) {
					cur_input.checked = false;
					checkGroup(group_id, false);
				}
				else if (cur_input.checked == false) {
					cur_input.checked = true;
					checkGroup(group_id, true);
				}				
			}
		}
	}
}

function toggle_force_check(state) {
	var check = document.getElementById('pers_force_label');
	if (check && typeof state != 'undefined') check.style.display = state;
}

function toggle_top(state) {
	var intro = document.getElementById('pers_intro');
	if (intro && typeof state != 'undefined') intro.style.display = state; 
}

function toggle_pers(state) {
	if (typeof state != 'undefined') document.getElementById('pers_main_row_holder').style.display = state;
}

function disable_commit() {
	var commiter = document.getElementById('commit_button');
	if (commiter) {
		commiter.disabled = true;
		if (get_file_name(commiter.src) == 'personalize_button.gif') commiter.src = '/global/images/buttons/personalize_grey.gif';
		else if (get_file_name(commiter.src) == 'save_and_continue.gif') commiter.src = '/global/images/buttons/save_and_continue_grey.gif';
	}
}
function enable_commit() {
	var commiter = document.getElementById('commit_button');
	if (commiter) {
		commiter.disabled = false;
		if (get_file_name(commiter.src) == 'personalize_grey.gif') commiter.src = '/global/images/buttons/personalize_button.gif';
		else if (get_file_name(commiter.src) == 'save_and_continue_grey.gif') commiter.src = '/global/images/buttons/save_and_continue.gif';
	}
}

function clearGroup(groupId) {
	var group_to_clear = new pers_util(groupId);
	group_to_clear.reset();
	
	if (group_to_clear.isActive()) {
		group_to_clear.focusFirst();
		if (force_checkbox() && document.getElementById('pers_force_label').style.display != 'none') {
			document.getElementById('pers_force_checkbox').checked = false;
		}
		enable_commit();
	}
	else {
		if (pers_list('active').length == 0 && !ajax_request()) disable_commit();
	}
}

function append_prod_list(name, price) {
	if ($('#p3_itemlist > li').length > 1) var nbsp = '&nbsp;';
	else var nbsp = '';
	
	$('#p3_itemlist').append('<li><div class="p3_itemradio">'+nbsp+'</div><div class="p3_itemname">'+name+'</div><div class="p3_itemprice">'+price+'</div></li>');
}

function delete_pers() {
	document.getElementById('pers_forms').innerHTML = '';
	if (!ajax_request()) {	
		var drop_rows = getElementsByAttribute('row_type', 'pers');
		for (i=0; i < drop_rows.length; i++) {
			drop_rows[i].parentNode.removeChild(drop_rows[i]);
		}
	}
}

function noPersCheck(state) {
	if (state == true) {
		resetForm();
		document.getElementById('pers_force_checkbox').checked = true;
		enable_commit();
	}
	else disable_commit();
}

function clean_unselected(groupId) {
	var cleaner = new pers_util(groupId);
	cleaner.clearUnselected();
}

function change_top_banner(img_name) {
	document.getElementById('pers_top_banner').src = '/global/images/personalization/'+img_name;
}

function ajax_submit(removeFlag) {
	if (!ajax_request()) return false;
	if (typeof removeFlag == 'undefined') var removeFlag = '';
	var query_string = new Array;
	
	var line_nodes = document.getElementById('pers_forms').childNodes;
	
	for (var y=0; y < line_nodes.length; y++) {
		var cur_node = line_nodes[y];
		if (cur_node.nodeType == 1 && cur_node.getAttribute('kind') == "pers_saved") {
			query_string.push(cur_node.name+'='+encodeURIComponent(cur_node.value));
		}
	}
	var cart_hash = document.pers.cart_hash.value;
	var line = document.pers.line_number.value;
	
	$.ajax({
		type: 'POST',
		url: '/global/modals/p3_personalization_panel.php',
		data: 'inc_pers=true&cart_hash='+cart_hash+'&line_number='+line+'&'+query_string.join('&')+removeFlag,
		success: function() {
			window.location = window.location.pathname + window.location.search;
		}
	});
	
	//ajaxCall('/tools/p3_personalization_panel.php?inc_pers=true&cart_hash='+cart_hash+'&line_number='+line+'&'+query_string.join('&')+removeFlag, 'window.location = window.location.pathname + window.location.search', 'post');
}

function qString(qname) {
	var query_string = window.location.search;
	query_string = query_string.substr(1,query_string.length-1);
	var queries = query_string.split('&');
	for (var i=0; i < queries.length; i++) {
		var cur_q = queries[i];
		cur_q = cur_q.split('=');
		if (cur_q[0] == qname) return cur_q[1];
	}
	return false;
}

function remove_all() {
	if (confirm('Are you sure you want to remove all personalizations from this product?')) ajax_submit('&remove_all_pers=true');
	return false;
}

function checkout_page() {
	//if (!ajax_request()) return false;
	switch (window.location.pathname) {
		case '/checkout/checkout.delivery.php': return 'delivery';
		case '/checkout/checkout.giftcard.php': return 'giftcard';
		case '/checkout/checkout.additional.php': return 'additional';
		case '/checkout/checkout.review.php': return 'review';
	}
	return false;
}

function selects_toggle(state) {
	var selects = document.getElementsByTagName('select');
	
	for (var g=0; g < selects.length; g++) {
		selects[g].style.visibility = state;
	}
} 

function metrics_info(metric_code) {
	return;
	
	var cart_hash = document.pers.cart_hash.value;
	if (!ajax_request()) var bpid = document.AddToCart.base_product_id.value;
	else var bpid = document.pers.bpid.value;
	if (!ajax_request()) var zip = document.AddToCart.v2_zip.value;
	else var zip = '';
	
	ajaxCall('/ajax_apps/pers_metrics.php?cart_hash='+cart_hash+'&bpid='+bpid+'&code='+metric_code+'&zip='+zip);
} 