// declare variables
var prescriptionForm = $('#prescriptionForm');
var usefor = $('#usefor');
var agree = $('#agree');
var p_as = $('#p_as');

// set prescription options hash object
var P = {};
P.lens_s = $('#lens_s');
P.lens_b = $('#lens_b');
P.lens_p = $('#lens_p');

P.diamond = $('#diamond');

P.division_1 = $('#division_1');
P.division_2 = $('#division_2');

P.od_sph = $('#od_sph');
P.od_cyl = $('#od_cyl');
P.od_axis = $('#od_axis');
P.od_add = $('#od_add');
P.os_sph = $('#os_sph');
P.os_cyl = $('#os_cyl');
P.os_axis = $('#os_axis');
P.os_add = $('#os_add');

P.noSamePd = $('#noSamePd');
P.pd = $('#pd');
P.npd = $('#npd');
P.left_pd = $('#left_pd');
P.right_pd = $('#right_pd');
P.extra = $('#extra');

P.index_150 = $('#index_150');
P.index_156 = $('#index_156');
P.index_159 = $('#index_159');
P.index_160 = $('#index_160');
P.index_167 = $('#index_167');
P.index_174 = $('#index_174');

P.p_ar = $('#p_ar');
P.p_uv = $('#p_uv');

P.tint = $('#tint');
P.tint_dropdown = $('#tint_dropdown');
P.photo = $('#photo');
P.photo_dropdown = $('#photo_dropdown');
P.diamond_checkbox = $('#diamond_checkbox');
P.diamond_dropdown = $('#diamond_dropdown');

P.categories_id = $('#categories_id');


// lenses
var lenses = P.index_150.add(P.index_156).add(P.index_159).add(P.index_160).add(P.index_167).add(P.index_174);

// protections
var protections = P.p_ar.add(P.p_uv);

// category id
var cId = P.categories_id.val() * 1;

/**
 * float variable
 */
$.floatval = function(v) {
	return parseFloat(v) || 0;
};

// calculate total price
var calculateTotal = function() {
	//var total = framePrice;
	var total = 0;

	$.each(P, function(k, v) {
		var price = v.attr('price');
		if (price && (v.attr('checked') || v.is('[type=hidden]'))) {
			total += $.floatval(price);
		}
	});

	total = total*batchCount;
	total += framePrice;
//	total = total*frameDiscount;
	total = total.toFixed(2);
	$('#totalPrice').html('$' + total);
	return total;
};

/**
 * set disabled function
 * @example
 *	xx.disabled() | xx.disabled(true) | xx.disabled(true, true)
 *	xx.disabled(false)
 */
$.fn.disabled = function(disabled, reset) {
	if (reset === undefined) reset = true;

	return this.each(function(){
		var $$ = $(this);

		if (disabled === false) {
			$$.removeAttr('disabled').removeClass('disabled');
		} else {
			if (reset) {
				if (!$$.is('#pd') && !$$.is('#npd') && !$$.is('#noSamePd') && !$$.is('#left_pd') && !$$.is('#right_pd')) {
					if ($$.is('select')) {
						if (!$$.is('#diamond_dropdown')) this.selectedIndex = 0;
					} else if ($$.is(':checkbox, :radio')) {
						this.checked = false;
					} else if ($$.is(':text')) {
						this.value = '';
					}
				}
			}

			$$.attr('disabled', 'disabled').addClass('disabled');
		}
	});
};

/**
 * change lens index
 * @example
 *	changeIndex(P.index_174)
 */
var changeIndex = function(lens) {
	if (lens.is(':checked')) {
		lenses.removeAttr('checked');
		lens.attr('checked', 'checked');
	} else {
		//lenses.removeAttr('checked');
		//lenses.eq(0).attr('checked', 'checked');
                selectIndex();
	}
};

var selectIndex = function() {
        lenses.removeAttr('checked');
        for (var t=0; t<lenses.length; t++) {
                if (!lenses.eq(t).is(':disabled')) {
                        lenses.eq(t).attr('checked', 'checked');
                        break;
                }
        }
};

/**
 * change division
 */
var changeDivision = function(division) {
	if (division.is(':checked')) {
		P.division_1.add(P.division_2).removeAttr('checked');
		division.attr('checked', 'checked');
	}
};

/**
 * filter color tint options
 * @example
 *	filterTint(20)
 *	filterTint(false)
 */
var filterTint = function(percent) {
	var opts = P.tint_dropdown.children();
	opts.each(function(){
		if (percent === false) {
			$(this).css('color', '').removeAttr('disabled');
		} else {
			var matches = this.text.match(/\s(\d+)%/);
			if (matches && matches[1] > percent) {
				$(this).css('color', '#ccc').attr('disabled', 'disabled');
			} else {
				$(this).css('color', '').removeAttr('disabled');
			}
		}
	});
};

// select different SPH
P.od_sph.add(P.os_sph).focus(function(){
	$(this).data('old', this.value);
}).change(function(){
	var $$ = $(this);
	if ($.floatval(P.od_sph[0].options[P.od_sph[0].selectedIndex].text) * $.floatval(P.os_sph[0].options[P.os_sph[0].selectedIndex].text) < 0) {
		$.confirm(PRODUCT_MSG_CONFIRM_DIFSPH, function(){}, function(){
			$$.val($$.data('old'));
		}, {title: ALERT_TITLE});
	}
});

// select different CYL
P.od_cyl.add(P.os_cyl).focus(function(){
	$(this).data('old', this.value);
}).change(function(){
	var $$ = $(this);
	if ($.floatval(P.od_cyl[0].options[P.od_cyl[0].selectedIndex].text) * $.floatval(P.os_cyl[0].options[P.os_cyl[0].selectedIndex].text) < 0) {
		$.confirm(PRODUCT_MSG_CONFIRM_DIFCYL, function(){}, function(){
			$$.val($$.data('old'));
		}, {title: ALERT_TITLE});
	}
});

// usefor
usefor.focus(function(){
	$(this).data('old', this.value);

}).change(function(){

	if (this.value == '') return;

	if (this.value == forFashion) {
		$.each(P, function(k, v){
			v.disabled();
		});
		lenses.add(P.tint).add(P.photo).add(P.diamond_checkbox).add(protections).disabled(false);
		checkIndex();

	} else if (this.value == forEverything) {
		if (!isBifocal) {
			$.alert(PRODUCT_MEX_1, function(){
				usefor.val(usefor.data('old'));
			}, {title: ALERT_TITLE});
			return;
		}
		$.each(P, function(k, v){
			v.disabled(false);
		});
		checkLensType();
		P.lens_s.disabled();

	} else {
		$.each(P, function(k, v){
			v.disabled(false);
		});
		P.lens_b.add(P.lens_p).removeAttr('checked');
		checkLensType();
	}

	checkAxis();
	checkDiamond();
	checkNpd();
	checkBifocal();
	calculateTotal();
});

// Bifocal & Progressive Lens
P.lens_b.click(function(){
	var $$ = $(this);
	if (this.checked) {
		if (usefor.val() != forEverything) {
			$.confirm(PRODUCT_MSG_CONFIRM_BL, function(){
				usefor.val(forEverything);
				P.lens_p.removeAttr('checked');

				checkNpd();
				checkBifocal();
				checkLensType();
				calculateTotal();
			}, function(){
				$$.removeAttr('checked');
			}, {title: ALERT_TITLE});
		} else {
			P.lens_p.removeAttr('checked');

			checkNpd();
			checkBifocal();
			checkLensType();
			calculateTotal();
		}
	}
	else {
		checkNpd();
		checkBifocal();
		checkLensType();
		calculateTotal();
	}
});

P.lens_p.click(function(){
	var $$ = $(this);
	if (this.checked) {
		if (usefor.val() != forEverything) {
			$.confirm(PRODUCT_MSG_CONFIRM_PL, function(){
				usefor.val(forEverything);
				P.lens_b.removeAttr('checked');

				checkNpd();
				checkBifocal();
				checkLensType();
				calculateTotal();
			}, function(){
				$$.removeAttr('checked');
			}, {title: ALERT_TITLE});
		} else {
			P.lens_b.removeAttr('checked');

			checkNpd();
			checkBifocal();
			checkLensType();
			calculateTotal();
		}
	} else {
		checkNpd();
		checkLensType();
		calculateTotal();
	}
});

// change index
lenses.click(function(){
	changeIndex($(this));
	checkIndex();
	calculateTotal();
});

// change division
P.division_1.add(P.division_2).click(function(){
	changeDivision($(this));
});

// tint & photochromic & diamond_checkbox
P.tint.click(function(){
	if (this.checked) {
		P.photo.removeAttr('checked');
	}
	checkTint();
	checkPhoto();
	calculateTotal();
});
P.photo.click(function(){
	if (this.checked) {
		P.tint.removeAttr('checked');
	}
	checkTint();
	checkPhoto();
	calculateTotal();
});
P.diamond_checkbox.click(function(){
	var pg = $('#partyGlasses');
	if (this.checked && pg.is(':hidden')) {
		pg.show($.browser.safari ? false : 'slow');
	} else if (!this.checked && pg.is(':visible')) {
		pg.hide($.browser.safari ? false : 'slow');
		P.diamond_dropdown[0][0].selected = true;
	}
	checkDiamond();
	calculateTotal();
});

// protections
protections.click(function(){
	calculateTotal();
});

// check bifocal
var checkBifocal = function() {
	P.division_1.add(P.division_2).disabled(!P.lens_b.is(':checked'));
};

// check npd
var checkNpd = function() {
	var everything = usefor.val() == forEverything;
	P.npd.disabled(!everything).parent().parent()[everything ? 'show' : 'hide']();
};

// check tint
var checkTint = function() {
	if (P.tint.is(':checked')) {
		P.tint_dropdown.disabled(false);

		if (P.index_167.is(':checked')) {
			filterTint(20);
		} else {
			filterTint(false);
		}
	} else {
		P.tint_dropdown.disabled();
	}
};

// check photochromic
var checkPhoto = function() {
	P.photo_dropdown.disabled(!P.photo.is(':checked'));
};

// check diamond_checkbox
var checkDiamond = function() {
	var colors = $('#partyGlasses td.colors a');
	P.diamond_dropdown.disabled(!P.diamond_checkbox.is(':checked'));

	colors.removeClass('current');
	if (P.diamond_dropdown.val()) {
		colors.filter(function(){
			return this.href.indexOf(P.diamond_dropdown.val()) != -1;
		}).addClass('current');
	}
};
P.diamond_dropdown.change(checkDiamond);

/**
 * added by Jcan - 2009.10.20
 */
var filterDegree = function(sphBgn, sphEnd, cylBgn, cylEnd) {
	var opts = P.od_sph.children().add(P.os_sph.children());
	opts.each(function(){
		if (sphBgn === false) {
			$(this).css('color', '').removeAttr('disabled');
		} else {
			var text = this.text, value = this.value, _text = parseFloat(text);
			if (_text === NaN && (value == 73 || value == 185) || _text < sphBgn || _text > sphEnd) {
				$(this).css('color', '#ccc').attr('disabled', 'disabled');
			} else {
				$(this).css('color', '').removeAttr('disabled');
			}
		}
	});

	opts = P.od_cyl.children().add(P.os_cyl.children());
	opts.each(function(){
		if (cylBgn === false) {
			$(this).css('color', '').removeAttr('disabled');
		} else {
			var text = this.text, value = this.value, _text = parseFloat(text);
			if (_text === NaN && (value == 117 || value == 229) || _text < cylBgn || _text > cylEnd) {
				$(this).css('color', '#ccc').attr('disabled', 'disabled');
			} else {
				$(this).css('color', '').removeAttr('disabled');
			}
		}
	});
};
var filterText = function($$, enabledArr, disabledArr) {
	var opts = $$.children();
	opts.each(function() {
		var text = this.text;
		if ($.inArray(text, enabledArr) != -1) {
			$(this).css('color', '').removeAttr('disabled');
		} else if ($.inArray(text, disabledArr) != -1) {
			$(this).css('color', '#ccc').attr('disabled', 'disabled');
		}
	});
};
var sphHandler = function() {
	var $$ = $(this).is('#od_sph') ? P.od_cyl : P.os_cyl;
	switch (this.options[this.selectedIndex].text) {
		case '-7.50':
			filterText($$, [], ['-2.25', '-2.50', '-2.75', '-3.00', '-3.25', '-3.50', '-3.75', '-4.00']);
			break;
		case '-7.25':
			filterText($$, ['-2.25'], ['-2.50', '-2.75', '-3.00', '-3.25', '-3.50', '-3.75', '-4.00']);
			break;
		case '-7.00':
			filterText($$, ['-2.25', '-2.50'], ['-2.75', '-3.00', '-3.25', '-3.50', '-3.75', '-4.00']);
			break;
		case '-6.75':
			filterText($$, ['-2.25', '-2.50', '-2.75'], ['-3.00', '-3.25', '-3.50', '-3.75', '-4.00']);
			break;
		case '-6.50':
			filterText($$, ['-2.25', '-2.50', '-2.75', '-3.00'], ['-3.25', '-3.50', '-3.75', '-4.00']);
			break;
		case '-6.25':
			filterText($$, ['-2.25', '-2.50', '-2.75', '-3.00', '-3.25'], ['-3.50', '-3.75', '-4.00']);
			break;
		case '-6.00':
			filterText($$, ['-2.25', '-2.50', '-2.75', '-3.00', '-3.25', '-3.50'], ['-3.75', '-4.00']);
			break;
		case '-5.75':
			filterText($$, ['-2.25', '-2.50', '-2.75', '-3.00', '-3.25', '-3.50', '-3.75'], ['-4.00']);
			break;
		default:
			filterText($$, ['-2.25', '-2.50', '-2.75', '-3.00', '-3.25', '-3.50', '-3.75', '-4.00'], []);
			break;
	}
};

// check index
var checkIndex = function() {
	if (lenses.filter(':checked').length == 0) {
		//P.index_150.attr('checked', 'checked');
                selectIndex();
	}

	filterDegree(false);
	P.od_sph.unbind('change', sphHandler);
	P.os_sph.unbind('change', sphHandler);

	if (P.index_150.is(':checked') || P.index_156.is(':checked')) {
		P.tint.add(P.photo).disabled(false);
	}
	else if (P.index_160.is(':checked') || P.index_167.is(':checked')) {
		P.tint.disabled(P.lens_b.is(':checked'));
		P.photo.disabled();
	}
	else if (P.index_159.is(':checked')) {
		P.tint.disabled();
		P.photo.disabled();

		// filter SPH & CYL
		// added by Jcan - 2009.10.20
		if (P.lens_b.is(':checked')) {
			filterDegree(-7.50, +4.75, -4.00, 0.00);
			P.od_sph.change(sphHandler);
			P.os_sph.change(sphHandler);
		} else {
			filterDegree(-6.00, +4.00, -2.00, 0.00);
		}
	}
	else if (P.index_174.is(':checked')) {
		P.tint.disabled();
		P.photo.disabled();
	}

	checkTint();
	checkPhoto();
};

// check bifocal & progressive
var checkLensType = function() {
	lenses.disabled(false);
	P.index_159.attr('checked', '');

	if (P.lens_b.is(':checked')) {
		P.lens_s.disabled();
		P.index_167.disabled();
		P.index_174.disabled();
	}
	else if (P.lens_p.is(':checked')) {
		P.lens_s.disabled();
		P.index_174.disabled();
		P.index_159.disabled();
	}
	else {
		P.lens_s.attr('checked', 'checked');
	}

	if (!lenses.filter(':checked').length) {
		lenses.eq(0).attr('checked', 'checked');
	}

	checkIndex();
};

// check PD
var checkPd = function() {
	if (P.noSamePd.is(':checked')) {
		P.pd.disabled().hide();
		if (usefor.val() == forFashion) {
			P.left_pd.add(P.right_pd).disabled().show();
		} else {
			P.left_pd.add(P.right_pd).disabled(false).show();
		}
	} else {
		if (usefor.val() == forFashion) {
			P.pd.disabled().show();
		} else {
			P.pd.disabled(false).show();
		}

		P.left_pd.add(P.right_pd).disabled().hide();
	}
};
P.noSamePd.click(checkPd);

// isPlano
var isPlano = function(val) {
	return $.inArray(val, ['99', '116', '118', '211', '228', '230']) != -1;
};

// check axis
var checkAxis = function() {
	P.od_axis.disabled(isPlano(P.od_cyl.val()));
	P.os_axis.disabled(isPlano(P.os_cyl.val()));
};
P.od_cyl.add(P.os_cyl).change(checkAxis);

// p_as
p_as.click(function(){this.checked = true;});

// init
var init = function() {
	checkNpd();
	p_as.attr('checked', 'checked');
	checkBifocal();
	checkLensType();
	calculateTotal();
	checkPd();
	checkAxis();
	checkDiamond();
	if (lenses.filter(':checked').length == 0) {
		changeIndex(P.index_150);
	}
	usefor.removeAttr('disabled')[0][0].text = 'Please Select';
};
setTimeout(init, 500);

// submit
var submitHandler = function(which) {
	var $$ = $(this);
	var self = this;

        var limit = [];

        //metal
        limit[51] = {275: [1.50, -5.00, 3.00, -3.00],
                     276: [1.57, -5.00, 4.00, -3.00],
                     277: [1.60, -5.00, 6.00, -4.00],
                     338: [1.67, -6.00, 7.00, -5.00],
                     339: [1.74, -10.0, 10.0, -5.00],
                     375: [1.59, -5.00, 4.00, -3.00]};

        //plastic
        limit[52] = {275: [1.50, -3.00, 2.50, -3.00],
                     276: [1.57, -3.50, 2.50, -3.00],
                     277: [1.60, -4.00, 3.50, -3.00],
                     338: [1.67, -5.00, 4.50, -4.00],
                     339: [1.74, -10.0, 10.0, -5.00],
                     375: [1.59, -3.50, 2.50, -3.00]};

        //rimless
        limit[53] = {275: [1.50, -3.00, 2.50, -2.00],
                     276: [1.57, -3.00, 2.50, -2.50],
                     277: [1.60, -4.00, 3.50, -2.50],
                     338: [1.67, -4.00, 3.00, -2.50],
                     339: [1.74, -4.00, 3.50, -3.00],
                     375: [1.59, -3.00, 2.50, -2.50]};

        //titanium
        limit[54] = {275: [1.50, -5.00, 3.00, -3.00],
                     276: [1.57, -5.00, 4.00, -3.00],
                     277: [1.60, -5.00, 6.00, -4.00],
                     338: [1.67, -6.00, 7.00, -5.00],
                     339: [1.74, -10.0, 10.0, -5.00],
                     375: [1.59, -5.00, 4.00, -3.00]};

	// check usefor
	if (usefor[0][0].selected) {
		$.alert(JS_ALERT_USAGE, function(){
			usefor.focus();
		}, {title: ALERT_TITLE});
		return false;
	}

	// check diamond
	if (P.diamond_dropdown.val() && !P.diamond_checkbox.attr('checked')) {
		var color = P.diamond_dropdown[0].options[P.diamond_dropdown[0].selectedIndex].text.toLowerCase();
		$.confirm('Please confirm you wish to add a ' + color + ' Swarovski crystal', function(){
			P.diamond_checkbox.attr('checked', 'checked');
			checkDiamond();
			submitHandler.call(self, which);
		}, function(){
			P.diamond_dropdown.val('');
			submitHandler.call(self, which);
		});
		return;
	}

	// check agree
	if (!agree.is(':checked')) {
		$.alert(JS_ALERT_TERMS, function(){
			agree.focus();
		}, {title: ALERT_TITLE});
		return false;
	}

	if (P.lens_b.is(':checked') || P.lens_p.is(':checked')) {
		if (P.od_sph[0][0].selected) {
			$.alert(JS_ALERT_RSPH, function(){
				P.od_sph.focus();
			}, {title: ALERT_TITLE});
			return false;
		}

		if (P.od_add[0][0].selected) {
			$.alert(JS_ALERT_RADD, function(){
				P.od_add.focus();
			}, {title: ALERT_TITLE});
			return false;
		}

		if (P.os_sph[0][0].selected) {
			$.alert(JS_ALERT_LSPH, function(){
				P.os_sph.focus();
			}, {title: ALERT_TITLE});
			return false;
		}

		if (P.os_add[0][0].selected) {
			$.alert(JS_ALERT_LADD, function(){
				P.os_add.focus();
			}, {title: ALERT_TITLE});
			return false;
		}
	}
	else if (usefor.val() == forEverything) {
		$.alert(PRODUCT_MSG_ALERT_BIFOCAL, function(){
			P.lens_b.focus();
		}, {title: ALERT_TITLE});
		return false;
	}

	if (!isPlano(P.od_cyl.val()) && !P.od_axis.val()) {
		$.alert(JS_ALERT_RAX, function(){
			P.od_axis.focus();
		}, {title: ALERT_TITLE});
		return false;
	}

	if (!isPlano(P.os_cyl.val()) && !P.os_axis.val()) {
		$.alert(JS_ALERT_LAX, function(){
			P.os_axis.focus();
		}, {title: ALERT_TITLE});
		return false;
	}

	// for PC piece
        var odSphIndex = P.od_sph[0].selectedIndex;
        if (odSphIndex != 0 && P.od_sph[0].options[odSphIndex].disabled) {
		$.alert(JS_ALERT_RSPH, function(){
			P.od_sph.focus();
		}, {title: ALERT_TITLE});
		return false;
        }
        var osSphIndex = P.os_sph[0].selectedIndex;
        if (osSphIndex != 0 && P.os_sph[0].options[osSphIndex].disabled) {
		$.alert(JS_ALERT_LSPH, function(){
			P.os_sph.focus();
		}, {title: ALERT_TITLE});
		return false;
        }

        var odCylIndex = P.od_cyl[0].selectedIndex;
        if (odCylIndex != 0 && P.od_cyl[0].options[odCylIndex].disabled) {
		$.alert('Please choose Right Eye Cylinder (CYL).', function(){
			P.od_cyl.focus();
		}, {title: ALERT_TITLE});
		return false;
        }
        var osCylIndex = P.os_cyl[0].selectedIndex;
        if (osCylIndex != 0 && P.os_cyl[0].options[osCylIndex].disabled) {
		$.alert('Please choose Left Eye Cylinder (CYL).', function(){
			P.os_cyl.focus();
		}, {title: ALERT_TITLE});
		return false;
        }


        if ($.inArray(cId, [51, 52, 53, 54]) > -1) {
                var limit_id = 0;

                for (var _t = 0; _t < lenses.length; _t++) {
                        if ($(lenses[_t]).is(':checked')) limit_id = $(lenses[_t]).val();
                }

                if (!limit_id*1) return false;

                var odSph = P.od_sph.get(0).options[P.od_sph.get(0).selectedIndex].text, odSphFirst = odSph.substr(0, 1);
                var osSph = P.os_sph.get(0).options[P.os_sph.get(0).selectedIndex].text, osSphFirst = osSph.substr(0, 1);
                var odCyl = P.od_cyl.get(0).options[P.od_cyl.get(0).selectedIndex].text;
                var osCyl = P.os_cyl.get(0).options[P.os_cyl.get(0).selectedIndex].text;
                var _lmt  = limit[cId][limit_id];

                odSph *= 1;
                osSph *= 1;
                odCyl *= 1;
                osCyl *= 1;

                if (odSph < _lmt[1] || odSph > _lmt[2] || osSph < _lmt[1] || osSph > _lmt[2] || odCyl < _lmt[3] || osCyl < _lmt[3]) {
                        $.confirm(PRODUCT_MSG_CHECKOUT_3,
                                  function() {
                                        goonSubmit($$);
                                  },
                                  function() {
                                        var indexIds = [150, 156, 159, 160, 167, 174];
                                        var currId = _lmt[0] * 100;
                                        for(var _t = 0; _t < indexIds.length; _t++) {
                                                if (currId >= indexIds[_t]) {
                                                        $('#index_' + indexIds[_t]).disabled();
                                                } else {
                                                        $('#index_' + indexIds[_t]).attr('checked', 'checked');;
                                                        break;
                                                }
                                        }
                                  },
                                  {'title': 'Warning', 'submit': 'Continue anyway', 'cancel': 'Upgrade lenses'});
                        return false;
                }
        }
        else if (P.index_150.is(':checked')) {
                var odSph = P.od_sph.get(0).options[P.od_sph.get(0).selectedIndex].text, odSphFirst = odSph.substr(0, 1);
                var osSph = P.os_sph.get(0).options[P.os_sph.get(0).selectedIndex].text, osSphFirst = osSph.substr(0, 1);
                if ((odSphFirst == '-' && parseFloat(odSph) < -6)
                        || (odSphFirst == '+' && parseFloat(odSph) > 4.5)
                        || (odSphFirst == '-' && parseFloat(odSph) < -6 )
                        || (odSphFirst == '+' && parseFloat(odSph) > 4.5)) {
                        $.alert(PRODUCT_MSG_CHECKOUT_1);
                        return false;
                }
        }

        goonSubmit($$, which);
};
var goonSubmit = function($$, which) {

        if (P.tint.is(':checked') && (P.tint_dropdown[0][0].selected || P.tint_dropdown[0].options[P.tint_dropdown[0].selectedIndex].disabled)) {
                $.alert(JS_ALERT_TINT, function(){
                        P.tint_dropdown.focus();
                }, {title: ALERT_TITLE});
                return false;
        }

        if (P.photo.is(':checked') && P.photo_dropdown[0][0].selected) {
                $.alert(JS_ALERT_PHOTO, function(){
                        P.photo_dropdown.focus();
                }, {title: ALERT_TITLE});
                return false;
        }

        if (P.diamond_checkbox.is(':checked') && P.diamond_dropdown[0][0].selected) {
                $.alert('Please select a color', function(){
                        P.diamond_dropdown.focus();
                }, {title: ALERT_TITLE});
                return false;
        }

        if (P.od_sph.is(':enabled') && P.od_sph[0][0].selected && P.od_cyl[0][0].selected && P.od_add[0][0].selected
                && P.os_sph[0][0].selected && P.os_cyl[0][0].selected && P.os_add[0][0].selected) {
                $.confirm(which == 1 ? PRODUCT_MSG_CONFIRM_NO_INFO : 'You have not provided a prescription. Save to cart?', function(){
                        $$[0].submit();
                }, null, {title: ALERT_TITLE});
                return false;
        }

        $$[0].submit();
};
prescriptionForm.submit(function(){
	prescriptionForm.attr('action', ACTION_URL_1);
	submitHandler.call(this, 1);
	return false;
});
$('#saveCartBtn').click(function(){
	prescriptionForm.attr('action', ACTION_URL_2);
	submitHandler.call(prescriptionForm, 2);
	return false;
});

// slideDown textarea
$('#pd2extra textarea').focus(function(){
	$(this).animate({
		height: 90
	}, 'fast', function(){
		this.focus();
	});
}).blur(function(){
	$(this).animate({
		height: 32
	});
});

// help tip
$('ins').hover(function(){
	var tip = $(this).data('arrowTip');
	var r = $(this).is('.r');
	tip && tip.remove();
	$(this).arrowTip(window[$(this).attr('id')], {
		arrow: {direction: 'bottom', height:16, width:16, side:r ? 0 : 16, offset:r ? 15 : -15},
		position: 2,
		distance: 2
	});
	$.browser.ie6 && $(this).data('arrowTip').tip.bgIframe({
		top: -1,
		left: -1,
		width: 314
	});
}, function(){
	var tip = $(this).data('arrowTip');
	tip && tip.remove();
});

// tint layer
//$('#tint_dropdown').focus(function(){
//	$(this).blur();
//	$('#tintLayer').fadeIn();
//});
//$('body').click(function(e){
//	if ($(e.target).is('not(#tint_dropdown)')) {
//		$('#tintLayer').fadeOut();
//	}
//});

// prescription
var usemyprescription = $('#usemyprescription');
var prescriptionInput = $('input[name=prescription_name]');

var deForm = function(hash) {
        var re = /\{((txt_)?(\d+))\}([^\{]*)/g;
        var matches = [], _row;
        while (_row = re.exec(hash)) {
                matches[matches.length] = _row;
        }

        for (var i=0, cnt=matches.length; i<cnt; i++) {
                var r = matches[i];
                var o = prescriptionForm.find('[name="id[' + r[1] + ']"]');
                if (r[1] == 'txt_33') {
                	P.noSamePd.attr('checked', 'checked').triggerHandler('click');
                }
                if (o.length) {
	                switch (o.get(0).type) {
	                        case 'text':
	                        case 'textarea':
	                        case 'select-one':
	                                o.val(r[4]).triggerHandler('click');
	                                o.triggerHandler('change');
	                                break;
	                        case 'checkbox':
	                        case 'radio':
	                                o.attr('checked', 'checked').triggerHandler('click');
	                                o.triggerHandler('change');
	                                break;
	                }
                }
        }
};
usemyprescription.change(function(){
	if (!this.value) {
		prescriptionInput.val('');
		return false;
	}
	deForm(this.value);
	init();
	agree.attr('checked', 'checked');
	prescriptionInput.val(this.options[this.selectedIndex].text);
});

// faq
var faqLayer = $('#faqLayer');
faqLayer.find('dl').hide().eq(0).show();
faqLayer.find('dd').hide();

$('#faqHandler').click(function(){
	$.lock(faqLayer, function(){

		this.find('h3').click(function(){
			var next = $(this).next();
			if (next.is(':visible')) {
				next.slideUp('fast', function(){
					$.layer.resizeHandler();
				});
			} else {
				var dl = $(this).siblings('dl:visible');
				if (dl.length) {
					$(this).siblings('dl:visible').slideUp('fast', function(){
						next.slideDown('fast', function(){
							$.layer.resizeHandler();
						})
					});
				} else {
					next.slideDown('fast', function(){
						$.layer.resizeHandler();
					})
				}
			}
		});

		this.find('dt').click(function(){
			var next = $(this).next();
			if (next.is(':visible')) {
				next.slideUp('fast', function(){
					$.layer.resizeHandler();
				});
			} else {
				var dd = $(this).parent().parent().find('dd:visible')
				if (dd.length) {
					dd.slideUp('fast', function(){
						next.slideDown('fast', function(){
							$.layer.resizeHandler();
						});
					});
				} else {
					next.slideDown('fast', function(){
						$.layer.resizeHandler();
					});
				}
			}
		});

		this.find('a.close').click(function(){
			$.unlock(function(){
				$(document).unbind('click');
			});
			return false;
		});

		$(document).click(function(e){
			if (!$(e.target).parents('#jqMsg').length) {
				$.unlock();
				$(document).unbind('click');
			}
		});
	});
	return false;
});

$('#contactHandler').click(function(){
	$.window($('#contactUs'), 'Contact Us');
	return false;
});

// no Prescription?
var noPrescriptionContent = $('#noPrescriptionContent');
noPrescriptionContent.find('dl').hide().eq(0).show();
noPrescriptionContent.find('dd').hide();
$('#noPrescriptionHandler').click(function(){
	$.lock(noPrescriptionContent, function(){

		var registerform = this.find('#registerBlock form');

		registerform.submit(function(){
			var $$ = $(this);
			var tip = $$.find('div.jsTip');

//			var gender = this.gender;
//			var firstname = this.firstname;
//			var lastname = this.lastname;
			var email = this.to_email_address;
//			var passwd = this.passwd;
//			var repasswd = this.repasswd;

			tip.check(!$.regexp.email.test(email.value), 'Invalid email address.', email)
			&& $$.ajaxForm(tip);
			return false;
		});

		this.find('a.close').click(function(){
			$.unlock(function(){
				$(document).unbind('click');
			});
			return false;
		});

		$(document).click(function(e){
			if (!$(e.target).parents('#jqMsg').length) {
				$.unlock();
				$(document).unbind('click');
			}
		});
	});
	return false;
});