var _ERROR = [
		'Please Update JScript\'s Version',
		'You do not have the definition of output',
		'Your firefox security restrictions limit you to the clipboard, please open your browser, type "about: config", set "signed.applets.codebase_principal_support" is true, then try again.' ];
var _COPY_STRING_ = '';
$( function() {
	$(':checkbox').click( function() {
		caculate();
	});
	$(':text').change( function() {
		caculate();
	});
	$('.check_it').click( function() {
		checkRecommend($(this));
	});
	$('.check_coupon_code').click( function() {
		check_coupon_code($(this));
	});
	$('.clear').click( function() {
		clear($(this));
	});
	$('#recaculate').click( function() {
		caculate();
	});
	caculate();

	if ($.browser.msie) {
		if ($.browser.version == '5.5') {
			alert(_ERROR[0])
		}
	}
	$('input[reg],textarea[reg]')
			.blur(
					function() {
						var _ = $(this);
						eval("reg = " + _.attr('reg'));
						var value = $.trim(_.attr('value'));
						_.attr('value', value);
						var name = _.attr('name');
						if (reg.test(value)) {
							var ajax = _.attr('ajax');
							if (typeof ajax != 'undefined') {
								var is_ajax = true;
								if ($('#old_' + name).length > 0) {
									if ($.trim($('#old_' + name).attr('value')) == value) {
										is_ajax = false;
										pass_stutas(_);
									}
								}
								if (is_ajax) {
									$.post(ajax, {
										field :name,
										val :value
									}, function(re) {
										if (re == "true") {
											$('.pass_img_' + name).remove();
											notes_content(_, _
													.attr('ajax_wrong'));
										} else {
											pass_stutas(_);
										}
									});
								}
							} else {
								var compare = _.attr('compare');
								var show_passed = _.attr('show_passed');
								if (typeof compare != 'undefined') {
									if (value == $.trim($('#' + compare).attr(
											'value'))) {
										pass_stutas(_);
									} else {
										$('.pass_img_' + name).remove();
										notes_content(_, _
												.attr('compare_wrong'));
									}
								} else if (typeof show_passed != 'undefined'
										& show_passed == 'no') {
									pass_stutas(_);
									$('.pass_img_' + name).remove();
								} else {
									pass_stutas(_);
								}
							}
						} else {
							$('.pass_img_' + name).remove();
							notes_content(_, _.attr('reg_wrong'));
						}
					});

	$('#copy_info').click( function() {
		var _t = $(this);
		if (_t.attr('checked')) {
			$('#NAMETOSHIP').val($('#NAME').val());
			$('#ADDRESSTOSHIP').val($('#ADDRESS').val());
			$('#CITYTOSHIP').val($('#CITY').val());
			$('#STATETOSHIP').val($('#STATE').val());
			$('#ZIPTOSHIP').val($('#ZIP').val());
		}
	});

	// textarea
	$('form')
			.submit(
					function() {
						var is_sub = true;
						$(this)
								.find('input, textarea')
								.each(
										function() {
											if (is_sub) {
												var is_form = $(this).attr(
														'is_form');
												if (typeof is_form != 'undefined') {
													$(this).blur();
													if ($('.pass_img_' + $(this)
															.attr('name')).length == 0) {
														is_sub = false;
														notes_content(
																$(this),
																$(this)
																		.attr(
																				'enter_value'));
													}
												} else {
													var reg = $(this).attr(
															'reg');
													var show_passed = $(this)
															.attr('show_passed');
													if ($(this).val() != ''
															&& typeof reg != 'undefined'
															&& show_passed != "no") {
														$(this).blur();
														if ($('.pass_img_' + $(
																this).attr(
																'name')).length == 0) {
															is_sub = false;
															notes_content(
																	$(this),
																	$(this)
																			.attr(
																					'enter_value'));
														}
													}
												}
											}
										});
						if (!is_sub) {
							return false;
						}
					});
});

function _id(id) {
	return document.getElementById(id);
}

function _g(e) {
	_COPY_STRING_ = e.dm72selection();
}

$.fn.dm72selection = function() {
	try {
		var s = '';
		if ($.browser.msie) {
			s = document.selection.createRange().text.toString();
		} else {
			s = window.getSelection().toString();
			if (s == '') {
				var d = _id($(this).attr('id'));
				if (d) {
					s = $(this).val().substr(d.selectionStart,
							d.selectionEnd - d.selectionStart);
				}
			}
		}
		return s;
	} catch (e) {
	}
}

function notes_content(o, notes) {
	notes = (typeof notes == 'string') ? notes : _ERROR[1];
	var os = o.offset();
	var name = o.attr('name');
	name = name.replace('\[\]', '');
	var x = os.left + o.width() - 20;
	var reverse = '';
	if (x + 260 > $('body').width()) {
		x = os.left - 260;
		if (x < 0) {
			x = 0;
		}
		reverse = '-reverse';
	}
	if ($('.notes_' + name).length == 0) {
		$('body')
				.append(
						'<div class="notes_' + name + '"><div></div><div></div><div></div></div>');
	}
	$('.notes_' + name).bgiframe();
	$('.notes_' + name)
			.css( {
				'position' :'absolute',
				'width' :'300px',
				'z-index' :'101',
				'top' :os.top,
				'left' :x
			})
			.find('div:first')
			.css('height', '5px')
			.html('<img src="' + url_start + '/files/img/order/notes-top.gif">')
			.next()
			.css(
					{
						'background' :'url(' + url_start + '/files/img/order/notes-bg.gif)',
						'padding-left' :'20px',
						'padding-right' :'20px'
					}).html('<div style="padding:3px;">' + notes + '</div>')
			.next().css('height', '9px').html(
					'<img src="' + url_start + '/files/img/order/notes-bottom'
							+ reverse + '.gif">');
	$('.notes_' + name).css('top', os.top - $('.notes_' + name).height())
}

$.fn.bgiframe = function(s) {
	// This is only for IE6
	if ($.browser.msie && parseInt($.browser.version) <= 6) {
		s = $.extend( {
			top :'auto', // auto == .currentStyle.borderTopWidth
			left :'auto', // auto == .currentStyle.borderLeftWidth
			width :'auto', // auto == offsetWidth
			height :'auto', // auto == offsetHeight
			opacity :true,
			src :'javascript:false;'
		}, s || {});
		var prop = function(n) {
			return n && n.constructor == Number ? n + 'px' : n;
		}, html = [
				'<iframe class="bgiframe" frameborder="0" tabindex="-1" src="' + s.src + '"',
				'style="display:block; position:absolute; z-index:-1;',
				s.opacity !== false ? 'filter:Alpha(Opacity=\'0\');' : '',
				'top:' + (s.top == 'auto' ? 'expression(((parseInt(this.parentNode.currentStyle.borderTopWidth)||0)*-1)+\'px\')'
						: prop(s.top)) + ';',
				'left:' + (s.left == 'auto' ? 'expression(((parseInt(this.parentNode.currentStyle.borderLeftWidth)||0)*-1)+\'px\')'
						: prop(s.left)) + ';',
				'width:' + (s.width == 'auto' ? 'expression(this.parentNode.offsetWidth+\'px\')'
						: prop(s.width)) + ';',
				'height:' + (s.height == 'auto' ? 'expression(this.parentNode.offsetHeight+\'px\')'
						: prop(s.height)) + ';', '"/>' ].join(' ');
		return this.each( function() {
			if ($('> iframe.bgiframe', this).length == 0)
				this
						.insertBefore(document.createElement(html),
								this.firstChild);
		});
	}
	return this;
};

function pass_stutas(obj) {
	var name = obj.attr('name');
	var img = url_start + '/files/img/order/yes.gif';
	if ($('.pass_img_' + name).length == 0) {
		obj.after('<img class="pass_img_' + name + '" src="' + img + '"/>')
	}
	$('.notes_' + name).remove();
}
function caculate() {
	$('span.total').text('Loading...');
	var _a = 0, _m = 0.00, _n = 0, _cd_n = 0, temp = 0.00;
	$("input.checked_id").val('');
	$("input.checked_place").val('');
	$("input.checked_exp").val('');
	$("input.cd_id").val('');
	$("input.cd_num").val('');
	$("input[id='id']")
			.each(
					function() {
						var _t = $(this);
						var sub_tr = $("#" + "tr_" + _t.val());
						if (_t.attr('checked')) {
							sub_tr.css("display", "");
							var _i = _t.parent().next().next().next().children(
									'input');
							var n = parseInt(_i.val().replace(/[^\d]/g, '') || '1');
							n = n < 1 ? 1 : n;
							var price_obj = _t.parent().next().next().next()
									.next().next().children('input');
							var per_price = price_obj.val();
							var exp_times_obj = _t.parent().next().next()
									.children('input');
							var exp_times = parseInt(exp_times_obj.val()
									.replace(/[^\d]/g, '')
									|| exp_times_obj.min("max"));
							_i.val(n);
							var exp_max = parseInt(exp_times_obj.attr("max"));
							$(
									'.notes_' + exp_times_obj.attr("name")
											.replace('\[\]', '')).remove();
							if (exp_max != 'undefined' && exp_times > exp_max) {
								exp_times = exp_max;
								notes_content(exp_times_obj, "The maximum is "
										+ exp_max + ".");
							}
							var exp_min = parseInt(exp_times_obj.attr("min"));
							$(
									'.notes_' + exp_times_obj.attr("name")
											.replace('\[\]', '')).remove();
							if (exp_min != 'undefined' && exp_times < exp_min) {
								exp_times = exp_min;
								notes_content(exp_times_obj, "The minimum is "
										+ exp_min + ".");
							}
							exp_times_obj.val(exp_times);
							if (n > 0) {
								_a += n;
								_m += per_price * 100 * exp_times * n;
								$("input.checked_place").val(
										$("input.checked_place").val() + ","
												+ n);
								$("input.checked_exp").val(
										$("input.checked_exp").val() + ","
												+ exp_times);
								$("input.checked_id").val(
										$("input.checked_id").val() + ","
												+ _t.val());
							}
						} else {
							sub_tr.css("display", "none");
						}
					});
	$("input[id='additional']")
			.each(
					function() {
						var _t = $(this);
						var product_checked = _t.parent().parent().prev()
								.children("td").children("input");
						var product_of_num = parseInt(product_checked.parent()
								.next().next().next().children('input').val());
						if (product_checked.attr('checked')
								&& _t.attr('checked')) {
							var _i = _t.parent().next().children('input');
							var of_cd_num = parseInt(_i.val().replace(/[^\d]/g,
									'') || '0');
							if (of_cd_num > 0) {
								if (of_cd_num > product_of_num) {
									of_cd_num = product_of_num;
								}
								_cd_n += of_cd_num;
								$("input.cd_id")
										.val(
												$("input.cd_id").val() + ","
														+ _t.val());
								$("input.cd_num").val(
										$("input.cd_num").val() + ","
												+ of_cd_num);
							}
							_i.val(of_cd_num);
						}
					});
	if (_a >= 1) {
		var all_cd_price = cd_price + shipping_price;
		temp = (all_cd_price * 100 * _cd_n);
		if ($("#check_coupon_code_status").val() == "yes"
				|| ($("#check_passed_1").val() == "yes" && $("#check_passed_2")
						.val() == "yes")) {
			_m = _m - 500;
		}
		_m = (_m + temp) / 100;
	} else {
		_m = 0;
	}
	var d = _m.toString().indexOf('.');
	if (d == -1) {
		_m = _m + '.00';
	} else if ((_m.toString().length - d) == 2) {
		_m = _m + '0';
	}
	$('span.total').text(_m);
	$('input.total').val(_m);
	$('#amount').val(_m);

	if (_m > 0.00) {
		$('#checkout').attr('disabled', '');
	} else {
		$('#checkout').attr('disabled', 'disabled');
	}
}
function checkOrder() {
	if ($.trim($("#coupon_code").val()) != "") {
		check_coupon_code();
	}
	if ($("#check_coupon_code_status").val() == "no"
			&& ($.trim($("#friend_email1").val()) != "" || $.trim($(
					"#friend_email2").val()) != "")) {
		checkRecommend($("#check_it1"));
		checkRecommend($("#check_it2"));
		if ($("#check_passed_1").val() != "yes"
				|| $("#check_passed_2").val() != "yes") {
			return false;
		}
	}
	caculate();
	var url = $('#order_url').val();
	$.post(url, {
		'checked_id' :$('#checked_id').val(),
		'cd_id' :$('#cd_id').val(),
		'cd_num' :$('#cd_num').val(),
		'school_id' :$("#school_id").val(),
		'coupon_code':$("#coupon_code").val(),
		'sid' :$('#sid').val(),
		'rid' :$('#rid').val(),
		'checked_place' :$('#checked_place').val(),
		'service_domain' :$('#service_domain').val(),
		'service_team' :$('#service_team').val(),
		'checked_exp' :$('#checked_exp').val(),
		'friend_name1' :$('#friend_name1').val(),
		'friend_name2' :$('#friend_name2').val(),
		'friend_email1' :$('#friend_email1').val(),
		'friend_email2' :$('#friend_email2').val(),
		'total' :$('#total').val()
	}, function(ret) {
		if (ret == "0") {
			alert("Order Failed.");
		} else {
			var bak_arr = ret.split(";");
			$('#order_number').val(bak_arr[0]);
			$('#orderForm').attr('action', url_start + "/order/credit/");
			$('#orderForm').submit();
		}
	});
	return false;
}
function check_coupon_code() {
	$.post(url_start + "/order/check_coupon_code/", {
		coupon_code :$("#coupon_code").val()
	}, function(re) {
		if (re == "false") {
			$("#check_coupon_code_status").val("no");
			$("#rid").val($("#oldrid").val());
			$('.pass_img_' + $("#coupon_code").attr("name")).remove();
			notes_content($("#coupon_code"), "Incorrect coupon code. Please re-enter it.");
		} else {
			$("#check_coupon_code_status").val("yes");
			$("#rid").val(re);
			caculate();
			pass_stutas($("#coupon_code"));
		}
		caculate();
	});
	return false;
}
function checkRecommend(obj) {
	var name_obj = obj.parent().prev().prev().children('input');
	var name_val = $.trim(name_obj.val());
	var email_obj = obj.parent().prev().children('input');
	var email_val = $.trim(email_obj.val());
	var cannot_same = email_obj.attr("cannot_same");
	var check_email_url = url_start + "/order/check_recommend/";
	var check_passed = obj.attr("place");
	if (name_val == "") {
		notes_content(name_obj, name_obj.attr("reg_wrong"));
		return false;
	}
	if (email_val == "") {
		notes_content(email_obj, email_obj.attr("reg_wrong"));
		return false;
	}
	if (typeof (cannot_same) != 'undefined') {
		var first_email = $("#" + cannot_same);
		var first_email_val = $.trim(first_email.val());
		if (first_email_val == email_val) {
			notes_content(email_obj, email_obj.attr("cannot_same_wrong"));
			return false;
		}
	}
	$.post(check_email_url, {
		email :email_val
	}, function(re) {
		if (re != "false") {
			$("#" + check_passed).val("no");
			$('.pass_img_' + email_obj.attr("name")).remove();
			notes_content(email_obj, re);
		} else {
			$("#" + check_passed).val("yes");
			pass_stutas(email_obj);
		}
		caculate();
	});
	return false;
}

