
function init()
{
	$('.reg-exception .yes')
		.click(function(){
			var apphost = 'http://' + window.location.host;
			window.location.href = apphost + '/register/register.php?exception_user_action';
		});

	$('.reg-exception .no')
		.click(function(){
			$('.reg-exception .please-contact').show();
		});
}


var barcode = {

	text: {
		invalid: "This barcode is invalid and not accepted.",
		just: "Barcode is not accepted because you have just added this barcode.",
		used: "This barcode was used before and not accepted.",
		more: "You can't add more barcodes than numbers of tickets in the order.",
		unissued: "This barcode is present in the DB but it has unissued status and not accepted.",
		linkedCurrent: "This barcode was linked with this Customer before.",
		linkedOther: "This barcode was linked with other Customer before."
	},

	extSys: true, // external system
	page: 'checkout',
	prevVal: false,
	ajaxRunning: false,
	checked: false,
	total: 0,


	init: function()
	{
		//alert('barcode.init');
		//$('#barcode').focus();
		if(barcode.page == 'checkout'){
			barcode.getReservedSeats();
		}
		setTimeout('barcode.watch()', 1500);
	},


	watch: function()
	{
		if(	String($('#barcode').val()).length == 12 &&
			barcode.ajaxRunning === false &&
			$('#barcode').val() != barcode.prevVal){

				var justAdded = false;

				if(barcode.page == 'checkout'){
					var reservedSeats = JSON.parse($('#barcode').data('reservedSeats'));
					var reservedSeatsTotal = Number($('#barcode').data('reservedSeatsTotal'));
					for(i=0; i<reservedSeatsTotal; i++){
						if(String(reservedSeats[i]['barcode_added']) == String($('#barcode').val())){
							justAdded = true;
							break;
						}
					}
				}

				if(!justAdded){
					barcode.prevVal = $('#barcode').val();
					barcode.checkDb();
				}
				else{
					alert(barcode.text.just);
					$('#barcode').val('');
				}
		}
		setTimeout('barcode.watch()', 1000);
	},


	checkDb: function()
	{
		$('#ajax-loader').show();
		barcode.ajaxRunning = true;
		var ajaxUrl = '/ajax/barcode.php?action=get&barcode=' + $('#barcode').val();
		var barcodeDb = ajaxRequest(ajaxUrl);

		//alert(barcodeDb); return;

		try{
			barcodeDb = JSON.parse(barcodeDb);
		}
		catch(e){
			alert(barcode.text.invalid);
		}

		if(barcodeDb){
			if(barcodeDb['order_num'] != null){
				alert(barcode.text.used);
			}
			else{
				if(barcode.page == 'checkout'){
					/*
					if(barcodeDb['contact_id'] != null){
						barcode.checkOrder(barcodeDb);
						$('#barcode').val('');
					}
					else{
						alert(barcode.text.unissued);
					}
					*/
					barcode.checkOrder(barcodeDb);
					$('#barcode').val('');
				}
				else{
					if(barcodeDb['contact_id'] != null){
						if(Number(barcodeDb['contact_id']) == Number($('#coupon_customer_id').val())){
							alert(barcode.text.linkedCurrent);
						}
						else{
							alert(barcode.text.linkedOther);
						}
					}
					else{
						barcode.checked = true;
						$('#barcode_checked').show();
					}
				}
			}
		}
		else{
			alert(barcode.text.invalid);
		}

		setTimeout(function(){
			$('#ajax-loader').hide();
			barcode.ajaxRunning = false;
		}, 1000);
	},


	checkOrder: function(barcodeDb)
	{
		var reservedSeats = JSON.parse($('#barcode').data('reservedSeats'));
		var reservedSeatsTotal = Number($('#barcode').data('reservedSeatsTotal'));

		//alert($('#barcode').data('reservedSeats'));

		for(i=0; i<reservedSeatsTotal; i++){
			if(reservedSeats[i]['barcode_added'] == 0){
				var ticketType = Number(reservedSeats[i]['ticket_type']) == 1 ? 'box' : 'ga';
				//alert('for #1' + '\n' + 'i = ' + i + '\n' + "barcodeDb['ticket_type'] = " + barcodeDb['ticket_type'] + '\n' + "ticketType = " + ticketType);
				if(
					barcodeDb['ticket_type'] == ticketType || 
					barcodeDb['ticket_type'] == 'box' || 
					(barcodeDb['ticket_type'] == 'ga' && ticketType == 'ga')){

					barcode.updateCheckout(i, barcodeDb);
					return;
					//break;
				}
				else{
					continue;
				}
			}
		}

		// $1.00 box seat upgrade
		for(i=0; i<reservedSeatsTotal; i++){
			if(reservedSeats[i]['barcode_added'] == 0){
				var ticketType = Number(reservedSeats[i]['ticket_type']) == 1 ? 'box' : 'ga';
				//alert('for #2' + '\n' + 'i = ' + i + '\n' + "barcodeDb['ticket_type'] = " + barcodeDb['ticket_type'] + '\n' + "ticketType = " + ticketType);
				if(barcodeDb['ticket_type'] == 'ga' && ticketType == 'box'){

					barcode.updateCheckout(i, barcodeDb);
					break;
				}
				else{
					continue;
				}
			}
		}

		// fix focus
		var attr = $('#barcode').attr('readonly');
		if(attr == false || attr == 'false' || attr == 'readonly'){
			$('#barcode').focus();
		}
	},


	updateCheckout: function(i, barcodeDb)
	{
		//alert('updateCheckout function');
		$('#accepted-barcodes').show();

		barcode.total++;
		var barcodeType = barcodeDb['ticket_type'];
		var eventId = $('#coupon_event_id').val();
		var reservedSeats = JSON.parse($('#barcode').data('reservedSeats'));
		var reservedSeatsTotal = Number($('#barcode').data('reservedSeatsTotal'));
		var ticketTypeId = Number(reservedSeats[i]['ticket_type']);
		var ticketType = ticketTypeId == 1 ? 'box' : 'ga';

		if(ticketType == 'box' && barcodeType == 'ga'){ // $1.00 box seat upgrade
			var optionCouponId = 6;
			var discount = '1.00';
		}
		else{
			var optionCouponId = ticketTypeId == 1 ? 1 : 2;
			var discount = reservedSeats[i]['ticket_price'];
		}

		var html =	'<input type="text" value="' + $('#barcode').val() + '" readonly="readonly" name="barcodes[]" /> ' + 
					'<span>barcode type: <b>' + barcodeType + '</b></span>' +
					'<span>ticket type: <b>' + ticketType + '</b></span>' +
					'<span>discount: <b>$' + discount + '</b></span><br />';
		$('#barcodes-container').append($(html));

		reservedSeats[i]['barcode_added'] = $('#barcode').val();
		$('#barcode').data('reservedSeats', JSON.stringify(reservedSeats));

		//alert('reservedSeatsTotal = ' + reservedSeatsTotal + '\n' + 'barcode.total = ' + barcode.total);

		if(reservedSeatsTotal == barcode.total){
			$('#barcode')
				.blur()
				.attr('readonly','readonly')
				.click(function(){
					alert(barcode.text.more);
					$(this).blur();
				});	
		}

		totalSum = Number($('#barcode_amt').val()) + Number(reservedSeats[i]['ticket_price']);

		$('#coupon_comments').val('Barcode');
		var selObj = document.getElementById('coupon_id');
		for(var k=0; k<selObj.length; k++){
			if(Number(selObj.options[k].value) == Number(optionCouponId)){
				selObj.selectedIndex = k;
				break;
			}
		}

		//alert('i = ' + i + "\n" + 'reservedSeats[i] = ' + JSON.stringify(reservedSeats[i]));

		var selObj = document.getElementById('coupon_event_id');
		for(var k=0; k<selObj.length; k++){
			if(Number(selObj.options[k].value) == Number(reservedSeats[i]['event_id'])){
				selObj.selectedIndex = k;
				break;
			}
		}

		createCoupon();
	},


	getReservedSeats: function()
	{
		var ajaxUrl = '/ajax/seats.php';
		var result = ajaxRequest(ajaxUrl);
		//alert('getReservedSeats: ' + result);
		$('#barcode').data('reservedSeats', result);
		$('#barcode').data('reservedSeatsTotal', JSON.parse(result).length);
	}

} // end barcode obj



var coupon = {

	text: {
		save: {
			type: 'Please select a "Coupon Type".',
			book: 'Please select a "Book #".',
			barcode: 'Please enter a barcode value.',
			success: 'Successfully saved.',
			error: 'An error occurred, please try again later.'
		}
	},

	mode: '',

	init: function(customerId)
	{
		$('#ajax-loader').show();
		setTimeout(function(){
			$('#coupon_customer_id').val(String(customerId));
			coupon.getSalespersons();
			barcode.page = 'customer';
			barcode.init();
		}, 1500);
	},


	getSalespersons: function()
	{
		var ajaxUrl = '/ajax/salespersons.php';
		var result = ajaxRequest(ajaxUrl);

		//alert(result);

		result = JSON.parse(result);
		var currentUserId = result['current_user_id'];
		result['current_user_id'] = null;
		$('#salesperson').data('currentUserId', currentUserId);

		$.each(result, function(key, value){   
			if(value){
				if(Number(currentUserId) != Number(value['user_id'])){
					var newOption = '<option></option>';
				}
				else{
					var newOption = '<option selected></option>';
				}
				$('#salesperson').append(
					$(newOption).val(String(value['user_id'])).html(String(value['full_name']))
				);
			}
		});
	},


	changeType: function()
	{
		var couponType = $('#coupon_type').val();
		//alert('coupon_type = [' + couponType + ']');

		if(couponType != ''){
			var data = String(couponType).split('_');
			var couponType = data[1];
			var couponQuantity = Number(data[2]);
			var couponValue = couponType == 'ga' ? 7 : 11;
			if(couponQuantity == 1){
				coupon.mode = 'barcode';
				$('#book_num').empty().attr('disabled', 'disabled');
				$('#book_num_container').hide();
				$('#barcode_container').show();
				$('#barcode').focus();
				setTimeout('barcode.watch()', 1000);
			}
			else{
				coupon.mode = 'book';
				$('#barcode_container').hide();
				$('#book_num_container').show();
				coupon.getBooks();
			}
			$('#coupon_quantity').removeAttr('disabled').attr('readonly', 'readonly').val(couponQuantity);
			$('#coupon_value').removeAttr('disabled').attr('readonly', 'readonly').val(couponQuantity * couponValue);
		}
		else{
			$('#book_num').empty().attr('disabled', 'disabled');
			$('#coupon_quantity').attr('disabled', 'disabled').val('');
			$('#coupon_value').attr('disabled', 'disabled').val('');
		}
	},


	getBooks: function()
	{
		var ajaxUrl = '/ajax/books.php?coupon_type=' + $("#coupon_type option:selected").val();
		var result = ajaxRequest(ajaxUrl);

		//alert('ajaxUrl = ' + ajaxUrl + '\n' + 'result = ' + result);
		result = JSON.parse(result);

		$('#book_num')
			.empty()
			.append($('<option value=""></option>').html('-- Select --'));

		$.each(result, function(key, value){   
			if(value){
				$('#book_num')
					.append($('<option></option>').val(String(value['book_num'])).html(String(value['book_num'])));
			}
		});

		$('#book_num').removeAttr('disabled');
	},


	save: function()
	{
		var couponType = $('#coupon_type').val();
		var bookNum = $('#book_num').val();
		var barcodeVal = $('#barcode').val();

		//alert(coupon.mode);

		if(couponType == 'select' || couponType == null){
			alert(coupon.text.save.type);
			return;
		}

		if(coupon.mode == 'barcode' && barcode.checked == false){
			alert(coupon.text.save.barcode);
			return;
		}

		if(coupon.mode == 'book' && (bookNum == '' || bookNum == null)){
			alert(coupon.text.save.book);
			return;
		}

		var ajaxUrl = '/ajax/barcode.php?' + 
						'action=update' + '&' +
						'couponYear=' + $('#coupon_year').val() + '&' +
						'bookNum=' + $('#book_num').val() + '&' +
						'barcode=' + $('#barcode').val() + '&' +
						'salePrice=' + $('#sale_price').val() + '&' +
						'customerId=' + $('#coupon_customer_id').val() + '&' +
						'salesperson=' + $('#salesperson').val() + '&' +
						'currentUserId=' + $('#salesperson').data('currentUserId');
		//alert(ajaxUrl); return;

		var result = ajaxRequest(ajaxUrl);
		//alert(result); return;

		if(result == 'success'){
			if(coupon.mode == 'book'){
				document.getElementById('coupon_type').options[0].selected = 'selected'; // jQuery does not work here...
				$('#book_num').empty().attr('disabled', 'disabled');
				$('#coupon_quantity').attr('disabled', 'disabled').val('');
				$('#coupon_value').attr('disabled', 'disabled').val('');
				$('#sale_price').val('');
			}
			else{
				$('#barcode_checked').hide();
				$('#barcode').val('').focus();
			}
			alert(coupon.text.save.success);
		}
		else{
			alert(coupon.text.save.error);
		}
	}

} // end coupon obj


function ajaxRequest(ajaxUrl)
{
	$('#ajax-loader').show();
	var apphost = 'http://' + window.location.host;
	//ajaxUrl = apphost + ajaxUrl;

	//alert('ajax request url: \n' + ajaxUrl);

	var result = $.ajax({
		url: ajaxUrl,
		async: false
	});
	var response = result.responseText;

	//alert('ajax response' + '\n\n' + response);

	/*
	try{
		return JSON.parse(response);
	}
	catch(e){
		return '';
	}
	*/

	setTimeout(function(){$('#ajax-loader').hide()},1000);
	return response;
}


function getObjectLength(obj) {
    var count = 0,
        key;

    for (key in obj) {
        if (obj.hasOwnProperty(key)) {
            count++;
        }
    }

    return count;
}


if(!this.JSON){JSON=function(){function f(n){return n<10?'0'+n:n;}
Date.prototype.toJSON=function(){return this.getUTCFullYear()+'-'+
f(this.getUTCMonth()+1)+'-'+
f(this.getUTCDate())+'T'+
f(this.getUTCHours())+':'+
f(this.getUTCMinutes())+':'+
f(this.getUTCSeconds())+'Z';};var m={'\b':'\\b','\t':'\\t','\n':'\\n','\f':'\\f','\r':'\\r','"':'\\"','\\':'\\\\'};function stringify(value,whitelist){var a,i,k,l,r=/["\\\x00-\x1f\x7f-\x9f]/g,v;switch(typeof value){case'string':return r.test(value)?'"'+value.replace(r,function(a){var c=m[a];if(c){return c;}
c=a.charCodeAt();return'\\u00'+Math.floor(c/16).toString(16)+
(c%16).toString(16);})+'"':'"'+value+'"';case'number':return isFinite(value)?String(value):'null';case'boolean':case'null':return String(value);case'object':if(!value){return'null';}
if(typeof value.toJSON==='function'){return stringify(value.toJSON());}
a=[];if(typeof value.length==='number'&&!(value.propertyIsEnumerable('length'))){l=value.length;for(i=0;i<l;i+=1){a.push(stringify(value[i],whitelist)||'null');}
return'['+a.join(',')+']';}
if(whitelist){l=whitelist.length;for(i=0;i<l;i+=1){k=whitelist[i];if(typeof k==='string'){v=stringify(value[k],whitelist);if(v){a.push(stringify(k)+':'+v);}}}}else{for(k in value){if(typeof k==='string'){v=stringify(value[k],whitelist);if(v){a.push(stringify(k)+':'+v);}}}}
return'{'+a.join(',')+'}';}}
return{stringify:stringify,parse:function(text,filter){var j;function walk(k,v){var i,n;if(v&&typeof v==='object'){for(i in v){if(Object.prototype.hasOwnProperty.apply(v,[i])){n=walk(i,v[i]);if(n!==undefined){v[i]=n;}}}}
return filter(k,v);}
if(/^[\],:{}\s]*$/.test(text.replace(/\\./g,'@').replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,']').replace(/(?:^|:|,)(?:\s*\[)+/g,''))){j=eval('('+text+')');return typeof filter==='function'?walk('',j):j;}
throw new SyntaxError('parseJSON');}};}();}
