// declare variables
var prescriptionForm = $('#prescriptionForm');
var usefor = $('#usefor');
var agree = $('#agree');
var p_as = $('#p_as');
var divisionsBlock = $('#divisionsBlock');
var trifocaloptsBlock = $('#trifocaloptsBlock');
var pcTip = $('#pcTip');
var index150Tip = $('#index150Tip');
var photoTip = $('#photoTip');

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

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

P.trifocalopt_1 = $('#trifocalopt_1');
P.trifocalopt_2 = $('#trifocalopt_2');

P.od_sph = $('#od_sph');
P.od_cyl = $('#od_cyl');
P.od_axis = $('#od_axis');
P.od_add = $('#od_add');
P.od_prismnum_v = $('#od_prismnum_v');
P.od_prismnum_h = $('#od_prismnum_h');
P.od_prismdir_v = $('#od_prismdir_v');
P.od_prismdir_h = $('#od_prismdir_h');
P.os_sph = $('#os_sph');
P.os_cyl = $('#os_cyl');
P.os_axis = $('#os_axis');
P.os_add = $('#os_add');
P.os_prismnum_v = $('#os_prismnum_v');
P.os_prismnum_h = $('#os_prismnum_h');
P.os_prismdir_v = $('#os_prismdir_v');
P.os_prismdir_h = $('#os_prismdir_h');

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.prism = $('#prism');

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.clipon_checkbox = $('#clipon_checkbox');
P.clipon_dropdown = $('#clipon_dropdown');

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

// lensTypes
var lensTypes = P.lens_s.add(P.lens_b).add(P.lens_p).add(P.lens_t);

// 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;
};

/**
 * get options text
 */
$.fn.getText = function(isint) {
	var retval = this[0].options[this[0].selectedIndex].text.replace(' ', '');
	if (isint) {
		return $.intval(retval);
	}
	return retval;
};

// 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.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'))
						if ($$.is('#od_sph')) $$.val(39);
						else if ($$.is('#os_sph')) $$.val(151);
						else if ($$.is('#od_cyl')) $$.val(99);
						else if ($$.is('#os_cyl')) $$.val(211);
						else this.selectedIndex = 0;
					} else if ($$.is(':checkbox, :radio')) {
						this.checked = false;
					} else if ($$.is(':text')) {
						this.value = '';
					}
				}
			}

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

/**
 * fix lens index
 * @example
 *	fixToIndex(P.index_174)
 */
var fixToIndex = function(lens) {
	if (lens.is(':checked')) {
		lenses.removeAttr('checked');
		lens.attr('checked', 'checked');
	}
};
//change default nothing select, Andy, 2010.03.18
var selectIndex = function(v) {
        if (v) {
                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 to the lens type and check the lens type
 */
var changeToLensType = function(lens) {
	lensTypes.disabled();
	lens.disabled(false).attr('checked', 'checked');
	checkLensType();
};

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

/**
 * change trifocal option
 */
var changeTrifocalopt = function(trifocalopt) {
	var trifocalopts = P.trifocalopt_1.add(P.trifocalopt_2);
	if (trifocalopt.is(':checked')) {
		trifocalopts.removeAttr('checked');
		trifocalopt.attr('checked', 'checked');
	} else {
		trifocalopts.attr('checked', 'checked');
		trifocalopt.removeAttr('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.getText()) * $.floatval(P.os_sph.getText()) < 0) {
		$.confirm(PRODUCT_MSG_CONFIRM_DIFSPH, function(){}, function(){
			$$.val($$.data('old'));
			checkPrescription();
		}, {title: ALERT_TITLE});
	}
	checkPrescription();
});

// 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.getText()) * $.floatval(P.os_cyl.getText()) < 0) {
		$.confirm(PRODUCT_MSG_CONFIRM_DIFCYL, function(){}, function(){
			$$.val($$.data('old'));
			checkPrescription();
		}, {title: ALERT_TITLE});
	}
	checkPrescription();
});

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

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

	var _endingCall = function() {
		checkPrism();
		checkAxis();
		checkPrescription();
		checkDiamond();
		checkClipOn();
		checkNpd();
		checkBifocal();
		checkTrifocal();
		calculateTotal();
	};

	if (this.value == forFashion) {
		divisionsBlock.hide();
		trifocaloptsBlock.hide();
		$.each(P, function(k, v){
			v.disabled();
		});
		lenses.add(P.tint).add(P.photo).add(P.diamond_checkbox).add(P.clipon_checkbox).add(protections).disabled(false);
		changeToLensType(P.lens_s);
	}
	else if (this.value == forBifocal) {
		if (!isBifocal) {
			if (isRimless) {
				$.confirm('Please be advised that as you have selected a bifocal lens the actual high of the lens might be slightly larger than in the frame details.', function() {
					divisionsBlock.show();
					trifocaloptsBlock.hide();
					$.each(P, function(k, v){
						v.disabled(false);
					});
					changeToLensType(P.lens_b);

					_endingCall();
				}, function() {
					usefor.val(usefor.data('old'));
				}, {title: ALERT_TITLE});
			} else {
				$.alert(PRODUCT_MEX_1, function(){
					usefor.val(usefor.data('old'));
				}, {title: ALERT_TITLE});
			}
			return;
		}
		divisionsBlock.show();
		trifocaloptsBlock.hide();
		$.each(P, function(k, v){
			v.disabled(false);
		});
		changeToLensType(P.lens_b);
	}
	else if (this.value == forProgressive) {
		if (!isProgressive) {
			if (isRimless) {
				$.confirm('Please be advised that as you have selected a progressive lens the actual high of the lens might be slightly larger than in the frame details.', function() {
					divisionsBlock.hide();
					trifocaloptsBlock.hide();
					$.each(P, function(k, v){
						v.disabled(false);
					});
					changeToLensType(P.lens_p);

					_endingCall();
				}, function() {
					usefor.val(usefor.data('old'));
				}, {title: ALERT_TITLE});
			} else {
				$.alert(PRODUCT_MEX_2, function(){
					usefor.val(usefor.data('old'));
				}, {title: ALERT_TITLE});
			}
			return;
		}
		divisionsBlock.hide();
		trifocaloptsBlock.hide();
		$.each(P, function(k, v){
			v.disabled(false);
		});
		changeToLensType(P.lens_p);
	}
	else if (this.value == forTrifocal) {

		if (!isTrifocal) {
			if (isRimless) {
				$.confirm('Please be advised that as you have selected a trifocal lens the actual high of the lens might be slightly larger than in the frame details.', function() {
					divisionsBlock.hide();
					trifocaloptsBlock.show();
					$.each(P, function(k, v){
						v.disabled(false);
					});
					changeToLensType(P.lens_t);

					_endingCall();
				}, function() {
					usefor.val(usefor.data('old'));
				}, {title: ALERT_TITLE});
			} else {
				$.alert('Sorry, this frame is not suitable for trifocal lenses.', function(){
					usefor.val(usefor.data('old'));
				}, {title: ALERT_TITLE});
			}
			return;
		}

		divisionsBlock.hide();
		trifocaloptsBlock.show();
		$.each(P, function(k, v){
			v.disabled(false);
		});
		changeToLensType(P.lens_t);
	}
	else {
		divisionsBlock.hide();
		trifocaloptsBlock.hide();
		$.each(P, function(k, v){
			v.disabled(false);
		});
		P.lens_b.add(P.lens_p).removeAttr('checked');
		changeToLensType(P.lens_s);
	}

	_endingCall();
});

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

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

// change trifocal option
P.trifocalopt_1.add(P.trifocalopt_2).click(function(){
	changeTrifocalopt($(this));
});

// tint & photochromic & diamond_checkbox
P.tint.click(function(){
	if (this.checked) {
		P.photo.removeAttr('checked');
	}
	checkTint();
	checkPhoto();
	calculateTotal();

	if (this.checked && P.clipon_checkbox.is(':checked')) {
		$.alert('You have selected to add clip-on sunglasses to a frame with tinted lenses. Unless you intend to use the clip-on sunglasses with another frame, we recommend removing one of the two',
			function() {},
			{'submit': 'I understand'}
		);
	}
});
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.slideDown('fast');
	} else if (!this.checked && pg.is(':visible')) {
		pg.slideUp('fast');
		P.diamond_dropdown[0][0].selected = true;
	}
	checkDiamond();
	calculateTotal();
});
P.clipon_checkbox.click(function(){
	var pg = $('#cliponGlasses');
	if (this.checked && pg.is(':hidden')) {
		pg.slideDown('fast');
	} else if (!this.checked && pg.is(':visible')) {
		pg.slideUp('fast');
		P.clipon_dropdown[0][0].selected = true;
	}
	checkClipOn();
	calculateTotal();

	if (this.checked && P.tint.is(':checked')) {
		$.alert('You have selected to add clip-on sunglasses to a frame with tinted lenses. Unless you intend to use the clip-on sunglasses with another frame, we recommend removing one of the two',
			function() {},
			{'submit': 'I understand'}
		);
	}
});

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

// goto next index
var toNextIndex = function($$) {
	var a = lenses.filter(':enabled'), c = $$ || lenses.filter(':checked');
	if (c[0] != P.index_159[0]) {
		a = a.not(P.index_159[0]);
	}
	if (!a.length) return false;

	if (!c.length) a.eq(0).attr('checked', 'checked');

	var i = a.index(c);
	if (i < a.length - 1) {
		a.removeAttr('checked');

		// promotion for index 160
		if (a.eq(i+1).is('#index_156') && P.index_160.is(':enabled')) {
			P.index_160.attr('checked', 'checked');
		}
		else {
			a.eq(i+1).attr('checked', 'checked');
		}
	}
};

var is160Index = function($$) {
	var a = lenses.filter(':enabled'), c = $$ || lenses.filter(':checked');
	if (c[0] != P.index_159[0]) {
		a = a.not(P.index_159[0]);
	}
	if (!a.length) return false;
	if (!c.length) return false;

	var i = a.index(c);
	if (i < a.length - 1) {
		if (a.eq(i+1).is('#index_156') && P.index_160.is(':enabled')) {
			return true;
		}
		return a.eq(i+1).is('#index_160');
	}
	return false;
};

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

// check trifocal
var checkTrifocal = function() {
	P.trifocalopt_1.add(P.trifocalopt_2).disabled(!P.lens_t.is(':checked'));
};

// check prescription.
var checkPrescription = function() {
	// check PC piece (index159)
	var bool = true;
	if (P.lens_b.is(':checked')) {
		if (bool = filterDegree(-6.00, +4.75, -2.00, 0.00, true)) {
			bool = sphHandler.call(P.od_sph[0], null, true) && sphHandler.call(P.os_sph[0], null, true);
		}
	} else if (P.lens_t.is(':checked')) {
		checkIndex();
		// check free index (index150)
		checkIndex150();
		calculateTotal();
		return;
	} else if (P.lens_p.is(':checked')) {
		bool = false;
	} else {
		bool = filterDegree(-6.00, +4.00, -2.00, 0.00, true);
	}

	if (bool) {
	        P.index_159.disabled(false);
	        pcTip.hide();
	} else {
		P.index_159.disabled();
		pcTip.show();

		if (!lenses.filter(':checked').length) {
			//////
			P.od_sph.unbind('change', sphHandler);
			P.os_sph.unbind('change', sphHandler);
			filterDegree(false);
		}
	}

	checkIndex();
	// check free index (index150)
	checkIndex150();
	calculateTotal();
};

// check npd
var checkNpd = function() {
	var val = usefor.val();
	var notSingle = (val == forBifocal || val == forProgressive || val == forTrifocal);
	P.npd.disabled(!notSingle).parent().parent()[notSingle ? 'show' : 'hide']();
};

// check tint and tint dropdown and tint percent
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'));
	photoTip[P.photo.is(':disabled') ? 'show' : 'hide']();
};

// 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);

// check clipon_checkbox
var checkClipOn = function() {
	var colors = $('#cliponGlasses .colors a');
	P.clipon_dropdown.disabled(!P.clipon_checkbox.is(':checked'));

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

// validate prescription
var validateDegree = function($$, min, max) {
	var text = $$.getText(), value = $.intval($$.val()), _text = parseFloat(text);
	if ($.inArray(value, [39, 74, 151, 186, 99, 118, 211, 230, 136, 248]) != -1) {
		_text = 0;
	}

	// isset min
	if (min || min === 0) {
		if (_text !== NaN && _text < min) return false;
	}
	// isset max
	if (max || max === 0) {
		if (_text === NaN && $.inArray(value, [73, 185, 117, 229]) != -1 || _text > max) {
			return false;
		}
	}
	return true;
};

// validate index150
var validateIndex150 = function() {
	   return validateDegree(P.od_sph, -6, +6)
	   	&& validateDegree(P.os_sph, -6, +6)
	   	&& validateDegree(P.od_cyl, -2)
	   	&& validateDegree(P.os_cyl, -2);
};

// check index150
var checkIndex150 = function() {
	if (validateIndex150()) {
		index150Tip.hide();
		P.index_150.disabled(false);
	} else {
		//if (P.index_150.is(':checked')) toNextIndex();
		index150Tip.show();
		P.index_150.disabled();
	}
};

/**
 * added by Jcan (for index 1.59) - 2009.10.20
 */
var filterDegree = function(sphBgn, sphEnd, cylBgn, cylEnd, onlytest, forever) {

	var retval = true, opts = onlytest
		? $(P.od_sph[0].options[P.od_sph[0].selectedIndex]).add($(P.os_sph[0].options[P.os_sph[0].selectedIndex]))
		: P.od_sph.children().add(P.os_sph.children()).not('[data-disabled]');

	if (sphBgn === false) {
		opts.css('color', '').removeAttr('disabled');
	} else {
		if (sphBgn != null & sphEnd != null) {
			opts.each(function(){
				var text = this.text.replace(' ', ''), value = this.value, _text = parseFloat(text);
				if (_text === NaN && (value == 73 || value == 185) || _text < sphBgn || _text > sphEnd) {
					if (onlytest) {
						retval = false;
						return false;
					}
					$(this).css('color', '#ccc').attr('disabled', 'disabled');
					if (forever) {
						$(this).attr('data-disabled', 'true');
					}
				} else {
					if (!onlytest) $(this).css('color', '').removeAttr('disabled');
				}
			});
		}
	}

	opts = onlytest
		? $(P.od_cyl[0].options[P.od_cyl[0].selectedIndex]).add($(P.os_cyl[0].options[P.os_cyl[0].selectedIndex]))
		: P.od_cyl.children().add(P.os_cyl.children()).not('[data-disabled]');

	if (sphBgn === false) {
		opts.css('color', '').removeAttr('disabled');
	} else {
		if (cylBgn != null && cylEnd != null) {
			opts.each(function(){
				var text = this.text.replace(' ', ''), value = this.value, _text = parseFloat(text);
				if (_text === NaN && (value == 117 || value == 229) || _text < cylBgn || _text > cylEnd) {
					if (onlytest) {
						retval = false;
						return false;
					}
					$(this).css('color', '#ccc').attr('disabled', 'disabled');
					if (forever) {
						$(this).attr('data-disabled', 'true');
					}
				} else {
					if (!onlytest) $(this).css('color', '').removeAttr('disabled');
				}
			});
		}
	}

	if (onlytest) return retval;
};

/**
 * added by Jcan - 2010.04.01
 */
var filterAdd = function(bgn, end, onlytest) {

	var retval = true, opts = onlytest
		? $(P.od_add[0].options[P.od_add[0].selectedIndex]).add($(P.os_add[0].options[P.os_add[0].selectedIndex]))
		: P.od_add.children().add(P.os_add.children());

	if (bgn === false) {
		opts.css('color', '').removeAttr('disabled');
	} else {
		opts.each(function(){
			var text = this.text.replace(' ', ''), _text = parseFloat(text);
			if (_text !== NaN && (_text < bgn || _text > end)) {
				if (onlytest) {
					return false;
				}
				$(this).css('color', '#ccc').attr('disabled', 'disabled');
			} else {
				if (!onlytest) $(this).css('color', '').removeAttr('disabled');
			}
		});
	}
};

var filterText = function($$, enabledArr, disabledArr, onlytest) {
	var retval = true, opts = onlytest === true ? $($$[0].options[$$[0].selectedIndex]) : $$.children();
	opts.each(function() {
		var text = this.text.replace(' ', '');
		if ($.inArray(text, enabledArr) != -1) {
			if (onlytest !== true) $(this).css('color', '').removeAttr('disabled');
		} else if ($.inArray(text, disabledArr) != -1) {
			if (onlytest === true) {
				retval = false;
				return false;
			}
			$(this).css('color', '#ccc').attr('disabled', 'disabled');
		}
	});
	return retval;
};
var sphHandler = function(e, onlytest) {
	var $$ = $(this).is('#od_sph') ? P.od_cyl : P.os_cyl;
	switch ($$.getText()) {
		case '-7.50':
			return filterText($$, [], ['-2.25', '-2.50', '-2.75', '-3.00', '-3.25', '-3.50', '-3.75', '-4.00'], onlytest);
			break;
		case '-7.25':
			return filterText($$, ['-2.25'], ['-2.50', '-2.75', '-3.00', '-3.25', '-3.50', '-3.75', '-4.00'], onlytest);
			break;
		case '-7.00':
			return filterText($$, ['-2.25', '-2.50'], ['-2.75', '-3.00', '-3.25', '-3.50', '-3.75', '-4.00'], onlytest);
			break;
		case '-6.75':
			return filterText($$, ['-2.25', '-2.50', '-2.75'], ['-3.00', '-3.25', '-3.50', '-3.75', '-4.00'], onlytest);
			break;
		case '-6.50':
			return filterText($$, ['-2.25', '-2.50', '-2.75', '-3.00'], ['-3.25', '-3.50', '-3.75', '-4.00'], onlytest);
			break;
		case '-6.25':
			return filterText($$, ['-2.25', '-2.50', '-2.75', '-3.00', '-3.25'], ['-3.50', '-3.75', '-4.00'], onlytest);
			break;
		case '-6.00':
			return filterText($$, ['-2.25', '-2.50', '-2.75', '-3.00', '-3.25', '-3.50'], ['-3.75', '-4.00'], onlytest);
			break;
		case '-5.75':
			return filterText($$, ['-2.25', '-2.50', '-2.75', '-3.00', '-3.25', '-3.50', '-3.75'], ['-4.00'], onlytest);
			break;
		default:
			return filterText($$, ['-2.25', '-2.50', '-2.75', '-3.00', '-3.25', '-3.50', '-3.75', '-4.00'], [], onlytest);
			break;
	}
};

// check index
// limit tint & photo by index
var checkIndex = function() {

	P.od_sph.unbind('change', sphHandler);
	P.os_sph.unbind('change', sphHandler);
	filterDegree(false);
	P.p_ar.disabled(false); // Andy, 2010.03.12

	switch (true) {
		case P.index_150.is(':checked'):
		case P.index_156.is(':checked'):
			if (P.lens_t.is(':checked')) {
				P.tint.disabled();
				P.photo.disabled();
			} else {
				P.tint.disabled(false);
				P.photo.disabled(false);
			}
			break;

		// only 1.499 for trifocal type, so donot need care for this here.
		case 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(-6.00, +4.75, -2.00, 0.00);
				P.od_sph.change(sphHandler);
				P.os_sph.change(sphHandler);
	                        P.p_ar.disabled(); // Andy, 2010.03.12
			} else {
				filterDegree(-6.00, +4.00, -2.00, 0.00);
			}
			break;

		case P.index_160.is(':checked'):
		case P.index_167.is(':checked'):
			P.tint.disabled(P.lens_b.is(':checked'));
			P.photo.disabled();
			break;

		case P.index_174.is(':checked'):
			P.tint.disabled();
			P.photo.disabled();
			break;

		default:
			break;
	}

	checkTint();
	checkPhoto();
};

// check single vision & bifocal & progressive & trifocal
// limit indeces by lens type
var checkLensType = function() {
	lenses.disabled(false);

	// anyway unchoose index_159 when the lens type is changed.
	P.index_159.attr('checked', '');
	filterAdd(false);

	if (P.lens_b.is(':checked')) {
		P.index_167.disabled();
		P.index_174.disabled();
	}
	else if (P.lens_p.is(':checked')) {
		P.index_174.disabled();
		P.index_159.disabled();
	}
	else if (P.lens_t.is(':checked')) {
		P.index_156.disabled();
		P.index_159.disabled();
		P.index_160.disabled();
		P.index_167.disabled();
		P.index_174.disabled();
		filterAdd(1.5, 3.5);
	}

	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;});

// frame limits
var frameLimits = function() {
	var arr, limits = {
		'MT1685': [-3, 1, null, null],
		'HTMT1139,HTMT1042,HTMT1140': [-3, 2, null, null],
		'HTMT1038,HTMT1039,HTMT1040,HTMT1041,HTMT1134,,IVDS0909,IVDS0910,IVDS0911,HTMT1038,HTMT1039,HTMT1040,HTMT1041,HTMT1134': [-4, 3, null, null],
		'HTRM0130,HTRM0139,HTRM0140,HTRM0141,HTRM0146,HTRM0147,HTRM0148,HTRM0149,HTRM0150,HTRM0151,HTRM0152,HTRM0153': [-5, 1, null, null],
		'HTMT1471,HTMT1472,HTMT1473,HTMT1474,HTMT1467,HTMT1468,HTMT1469,HTMT1470': [-4, 3, -2, 2],
		'JXMT1501,JXMT1502,JXMT1503,JXMT1504,JXMT1505': [-4, 3, null, null],
		'JXMT1513,JXMT1514,JXMT1515': [-4, 3, -2, 2],
		'MT1165,MT1166,MT1167,MT1168,MT1174,MT1175,MT1193,MT1194,MT1196,MT1197,MT1198,MT1199,MT1200': [-4, 3, null, null]
	};

	for (var s in limits) {
		if (s.indexOf(model) == -1) continue;
		arr = limits[s];
		filterDegree(arr[0], arr[1], arr[2], arr[3], false, true);
		return;
	}
	return true;
};

// init
var init = function() {
	switch ($.intval(usefor.val())) {
		case forBifocal:
			divisionsBlock.show();
			break;
		case forTrifocal:
			trifocaloptsBlock.show();
			break;
	}

	frameLimits();
	checkNpd();
	p_as.attr('checked', 'checked');
	checkBifocal();
	checkIndex150();
	checkLensType();
	checkPrescription();
	checkPd();
	checkAxis();
	checkDiamond();
	checkClipOn();
	if (lenses.filter(':checked').length == 0) {
		fixToIndex(P.index_150);
	}
	checkPrism();
	usefor.removeAttr('disabled')[0][0].text = TIP_PLZ_SELECT;
	calculateTotal();
};
setTimeout(init, 500);

var upgradedSign = false;

//Andy, 2010.03.18
var lensesCheckHandler = function() {

        /**
         * upgrade lens - changed by Jcan, 2010.02.02
         */
        if (!upgradedSign && $.inArray(cId, [51, 52, 53, 54]) != -1) {

                var lmts = {};

                //metal
                lmts[51] = {
                        275: [-5.00, 3.00, -3.00], // 150
                        276: [-5.00, 4.00, -3.00], // 156
                        277: [-5.00, 6.00, -4.00], // 160
                        338: [-6.00, 7.00, -5.00], // 167
                        339: [-10.0, 10.0, -5.00], // 174
                        375: [-5.00, 4.00, -3.00]}; // 159

                //plastic
                lmts[52] = {
                        275: [-3.00, 2.50, -3.00],
                        276: [-3.50, 2.50, -3.00],
                        277: [-4.00, 3.50, -3.00],
                        338: [-5.00, 4.50, -4.00],
                        339: [-10.0, 10.0, -5.00],
                        375: [-3.50, 2.50, -3.00]};

                //rimless
                lmts[53] = {
                        275: [-3.00, 2.50, -2.00],
                        276: [-3.00, 2.50, -2.50],
                        277: [-4.00, 3.50, -2.50],
                        338: [-4.00, 3.00, -2.50],
                        339: [-10.0, 10.0, -5.00],
                        375: [-3.00, 2.50, -2.50]};

                //titanium
                lmts[54] = {
                        275: [-5.00, 3.00, -3.00],
                        276: [-5.00, 4.00, -3.00],
                        277: [-5.00, 6.00, -4.00],
                        338: [-6.00, 7.00, -5.00],
                        339: [-10.0, 10.0, -5.00],
                        375: [-5.00, 4.00, -3.00]};

                var lmt = lmts[cId][$.intval(lenses.filter(':checked').val())];
                if (!lenses.filter(':enabled:last').is(':checked') && (!validateDegree(P.od_sph, lmt[0], lmt[1])
                        || !validateDegree(P.os_sph, lmt[0], lmt[1]) || !validateDegree(P.od_cyl, lmt[2]) || !validateDegree(P.os_cyl, lmt[2]))) {
                        upgradedSign = true;
                        $.confirm(
                                PRODUCT_MSG_CHECKOUT_3, // + (is160Index() ? '<br /><img src="' + LENS_PROMOTION_IMG + '" width="460" height="120" />' : ''),
                                function() {
                                        toNextIndex();
                                        checkIndex();
                                        calculateTotal();

                                },
                                function() {
                                        return ;
                                },
                                {'title': '', 'submit': 'Upgrade Now', 'cancel': 'No Thanks', 'focus': 'submit'}
                        );
                        return false;
                }
        }
};

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

	if (lenses.filter(':checked').length == 0) {
		$.alert('Please choose the lens thickness.', function() {
			lenses.filter(':enabled:first').focus();
		}, {title: ALERT_TITLE});
		return false;
		// selectIndex(true); //Must select one lens type, Andy, 2010.03.18
	}

	// 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.getText().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 clipon
	if (P.clipon_dropdown.val() && !P.clipon_checkbox.attr('checked')) {
		var color = P.clipon_dropdown.getText().toLowerCase();
		$.confirm('Please confirm you wish to add a ' + color + ' clip on.', function(){
			P.clipon_checkbox.attr('checked', 'checked');
			checkClipOn();
			submitHandler.call(self, which);
		}, function(){
			P.clipon_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') || P.lens_t.is(':checked')) {

		if (usefor.val() == forBifocal && !P.division_1.is(':checked') && !P.division_2.is(':checked')) {
			$.alert('Please select the distance / reading proportion of your bifocal lens.', function(){
				P.division_1.focus();
			}, {title: ALERT_TITLE});
			return false;
		}

		if (usefor.val() == forTrifocal && !P.trifocalopt_1.is(':checked') && !P.trifocalopt_2.is(':checked')) {
			$.alert('Please select the portion details of your trifocal lens.', function(){
				P.trifocalopt_1.focus();
			}, {title: ALERT_TITLE});
			return false;
		}

		if (P.od_sph[0].options[P.od_sph[0].selectedIndex].text.match(/none/)) {
		// 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 || P.od_add[0].options[P.od_add[0].selectedIndex].disabled) {
			$.alert(JS_ALERT_RADD, function(){
				P.od_add.focus();
			}, {title: ALERT_TITLE});
			return false;
		}

		if (P.os_sph[0].options[P.os_sph[0].selectedIndex].text.match(/none/)) {
		// 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 || P.os_add[0].options[P.os_add[0].selectedIndex].disabled) {
			$.alert(JS_ALERT_LADD, function(){
				P.os_add.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 selectedOpt = P.od_sph[0].options[P.od_sph[0].selectedIndex];
        if (!selectedOpt.text.match(/none/) && selectedOpt.disabled) {
		$.alert('Please choose the Right Eye Sphere (SPH).', function(){
			P.od_sph.focus();
		}, {title: ALERT_TITLE});
		return false;
        }
	var selectedOpt = P.os_sph[0].options[P.os_sph[0].selectedIndex];
        if (!selectedOpt.text.match(/none/) && selectedOpt.disabled) {
		$.alert('Please choose Left Eye Sphere (SPH).', function(){
			P.os_sph.focus();
		}, {title: ALERT_TITLE});
		return false;
        }

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

        if (P.prism.is(':checked')) {
        	if (Math.abs($.floatval(P.od_sph.getText())) + Math.abs($.floatval(P.od_cyl.getText())) + Math.max(Math.abs($.floatval(P.od_prismnum_v.getText())), Math.abs($.floatval(P.od_prismnum_h.getText()))) > 10) {
			$.alert('The absolute sum of the values entered in SPH + CYL + Prism cannot exceed 10.', function() {
				P.od_prismnum_v.focus();
			}, {title: ALERT_TITLE});
			return false;
        	}

        	if (Math.abs($.floatval(P.os_sph.getText())) + Math.abs($.floatval(P.os_cyl.getText())) + Math.max(Math.abs($.floatval(P.os_prismnum_v.getText())), Math.abs($.floatval(P.os_prismnum_h.getText()))) > 10) {
        		$.alert('The total sum of the values entered in SPH + CYL + Prism cannot exceed 10.', function() {
				P.os_prismnum_v.focus();
			}, {title: ALERT_TITLE});
			return false;
        	}

        	if (P.od_prismnum_v[0][0].selected && P.od_prismnum_h[0][0].selected && P.os_prismnum_v[0][0].selected && P.os_prismnum_h[0][0].selected) {
        		$.alert('Please choose the prism value.', function() {
	        		P.od_prismnum_v.focus();
        		}, {title: ALERT_TITLE});
        		return false;
        	}

		if (!P.od_prismnum_v[0][0].selected && P.od_prismdir_v[0][0].selected) {
			$.alert('Please choose the base direction of your prism.', function() {
				P.od_prismdir_v.focus();
			}, {title: ALERT_TITLE});
			return false;
		}
		if (!P.od_prismnum_h[0][0].selected && P.od_prismdir_h[0][0].selected) {
			$.alert('Please choose the base direction of your prism.', function() {
				P.od_prismdir_h.focus();
			}, {title: ALERT_TITLE});
			return false;
		}

		if (!P.os_prismnum_v[0][0].selected && P.os_prismdir_v[0][0].selected) {
			$.alert('Please choose the base direction of your prism.', function() {
				P.os_prismdir_v.focus();
			}, {title: ALERT_TITLE});
			return false;
		}
		if (!P.os_prismnum_h[0][0].selected && P.os_prismdir_h[0][0].selected) {
			$.alert('Please choose the base direction of your prism.', function() {
				P.os_prismdir_h.focus();
			}, {title: ALERT_TITLE});
			return false;
		}
        }

        if (P.index_150.is(':checked') && !validateIndex150()) {
                $.alert(PRODUCT_MSG_CHECKOUT_1);
                return false;
        }

        // check selected index
        if (!lenses.filter(':enabled:checked').length) {
                $.alert('Please choose lens thickness.', function(){
                        lenses.filter(':enabled:first').focus();
                }, {title: ALERT_TITLE});
                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.clipon_checkbox.is(':checked') && P.clipon_dropdown[0][0].selected) {
                $.alert('Please select a color', function(){
                        P.clipon_dropdown.focus();
                }, {title: ALERT_TITLE});
                return false;
        }

        if (P.od_sph.is(':enabled')
        	&& P.od_sph[0].options[P.od_sph[0].selectedIndex].text.match(/none/)
        	&& P.od_cyl[0].options[P.od_cyl[0].selectedIndex].text.match(/none/)
        	&& P.od_add[0][0].selected
        	&& P.os_sph[0].options[P.os_sph[0].selectedIndex].text.match(/none/)
        	&& P.os_cyl[0].options[P.os_cyl[0].selectedIndex].text.match(/none/)
        	&& P.os_add[0][0].selected) {
        //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 $$ = $(this);
	//var usefor = $$.is('#Tip_usefor');
	var tip = $$.data('arrowTip');
	var r = $$.is('.r');
	var w = $.intval($$.attr('w') || 300);
	tip && tip.remove();
	$$.arrowTip(window[$$.attr('id')], {
		arrow: {direction: usefor ? 'top' : 'bottom', height:16, width:16, side:r ? 0 : 16, offset:r ? 15 : -15},
		position: usefor ? 8 : 2,
		distance: 2,
		css: {width: w + 'px'}
	});
	$.browser.ie6 && $$.data('arrowTip').tip.bgIframe({
		top: -1,
		left: -1,
		width: w + 14
	});
}, function(){
	var tip = $(this).data('arrowTip');
	tip && tip.remove();
});

// 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 'hidden':
	                        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(){
        usefor.val('');
        $.each(P, function(k, v){
                v.disabled(false);
        });

	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;
});

$('#prism').click(function() {
	checkPrism();
});

var checkPrism = function() {
	if (!P.prism.length) return;
	var checked = P.prism.is(':checked');

	$('#prismTable')[checked ? 'show' : 'hide']();
	$('#prismHandler .price')[checked ? 'show' : 'hide']();
	$('#od_prismnum_v, #od_prismnum_h, #os_prismnum_v, #os_prismnum_h, #od_prismdir_v, #od_prismdir_h, #os_prismdir_v, #os_prismdir_h').disabled(checked ? false : true);
	calculateTotal();
};
