﻿
(function ($) {
	keyCustomization = function (selector, options) {
		this.content = null;
		this.popup = null;
		this.options = $.extend({}, this.defaults, options);
		this.init();
	};

	keyCustomization.prototype = {
		init: function () {
			this.showKeyCustomizationPopup();
		},

		showKeyCustomizationPopup: function () {
			if (!this.content) {
				this.createContent();
			}
			this.keyCustomizationLoadData();
			this.initializeComponent();
			this.popup = this.createKeyCustomizationPopup();
		},

		initializeComponent: function () {
			$('#saveBtn', this.content).click(Function.createDelegate(this, this.saveKeyHandler));
			$('#cancelBtn', this.content).click(Function.createDelegate(this, this.cancelHandler));
			$('#buttonLabel', this.content).keyup(Function.createDelegate(this, this.buttonLabelChanged));
			$('#defaultPrice', this.content).keyup(Function.createDelegate(this, this.priceChanged));
			$('#discountValue', this.content).keyup(Function.createDelegate(this, this.discountValueChanged));
		},

		buttonLabelChanged: function (event) {
			$('#preview dl dt').html(htmlEncode($(event.target).val()));
		},

		priceChanged: function (event) {
			var price = parseFloat($(event.target).val());
			$('#preview dl dd').html(price ? '$' + price.toFixed(2) : '');
		},

		discountValueChanged: function (event) {
			var value = parseFloat($(event.target).val());
			if (value) {
				var isPercent = ($('input[name=valuePercentSelector]:checked').val() === 'True');
				$('#preview dl dd').html(isPercent ? value.toFixed(2) + '%' : '$' + value.toFixed(2));
			} else {
				$('#preview dl dd').html('');
			}
		},

		colorChanged: function (event) {
			$('#preview').attr('class', 'st keys-st' + $(event.target).val());
		},


		keyTypeChangedHandler: function (event) {
			$('#deptKeyList').toggle();
			$('#discountKeyList').toggle();

			var eventToFire = new Object();
			if ($(event.target).val() == '4') {
				$('#discountValue').keyup();
				$('#preview dl dt').html('Discount');
			}
			else {
				$('#defaultPrice').keyup();
				$('#buttonLabel').keyup();
			}
		},

		valueTypeChangedHandler: function (event) {
			var isPercent = ($('input[name=valuePercentSelector]:checked').val() === 'True');
			var discountValue = $('#discountValue');
			if (isPercent) {
				discountValue.attr('maxlength', '4');
				discountValue.unmaskMoney();
				$('#defaultPrice').unmaskMoney();
			} else {
				discountValue.attr('maxlength', '5');
				discountValue.maskMoney();
				$('#defaultPrice').maskMoney();
			}
			discountValue.keyup(event);
		},


		cancelHandler: function () {
			this.popup.hide();
		},

		saveKeyHandler: function () {
			var buttonLabel;
			var color = $('input[name=radio_color]:checked', this.content).val() || 1;
			var keyType = $('input[name=keySelector]:checked').val();
			var price;
			if (keyType != '4') {
				price = $('#defaultPrice', this.content).val();
				buttonLabel = $('#buttonLabel', this.content).val();
			}
			else {
				price = $('#discountValue', this.content).val();
				buttonLabel = 'Discount';
			}
			var deptName = $('#deptName', this.content).val();
			var taxRate = $('#taxRateList').val();
			var isPercent = ($('input[name=valuePercentSelector]:checked').val() === 'True');

			params = {
				request: this.options.keyUpdateRequest,
				keyNumber: this.options.keyNumber,
				keyType: keyType,
				buttonLabel: buttonLabel,
				color: color,
				deptName: deptName,
				defaultPrice: price,
				taxRate: taxRate,
				isPercent: isPercent
			};

			jQuery.ajax({
				type: 'POST',
				url: this.options.serviceUrl,
				data: params,
				dataFilter: $.msDataFilter,
				success: Function.createDelegate(this, this.updateKeyRequestCompleteHandler),
				error: Function.createDelegate(this, this.updateKeyRequestErrorHandler)
			});
		},

		updateKeyRequestCompleteHandler: function (data, result) {
			if (typeof data != undefined) {
				if (data.IsSuccess) {
					$('#key_' + this.options.keyNumber).attr('class', 'st keys-st' + data.Color);
					$('#key_' + this.options.keyNumber + ' dl dt').html(data.ButtonLabel);
					$('#key_' + this.options.keyNumber + ' dl dd').html(data.Price);
					$('#key_' + this.options.keyNumber).parent().addClass('assigned');
					$('#key_' + this.options.keyNumber).parent().draggable('enable');
					this.popup.hide();
				}
				else {
					this.showUpdateKeyRequestErrorMessage(data.ErrorMessage);
				}
			}
		},

		updateKeyRequestErrorHandler: function (response, result) {
			$.log('WARN', response.responseText);
			this.popup.hide();
			alert('Some errors was occured. Please try again later.');
		},

		showUpdateKeyRequestErrorMessage: function (message) {
			$('form').messageBox(null, {
				messageType: 'Error',
				top: 10,
				width: 350,
				autoClose: true,
				containerClassName: 'popup-window ontop',
				title: "One or more errors have been detected",
				modal: false
			},
			$.generateList, { list: [message] });
		},

		createKeyCustomizationPopup: function () {
			return $('form').messageBox(null, {
				messageType: '',
				contentClassName: '',
				title: 'Button Properties',
				width: 500,
				top: 150,
				modal: true,
				autoClose: false,
				innerRound: 0
			}, this.content);
		},

		createContent: function () {
			this.content = $.create('div', {});
			this.content.setTemplateURL(this.options.templateUrl, null, { filter_data: false });
			this.content.processTemplate(null);
		},

		keyCustomizationLoadData: function () {
			params = {
				request: this.options.keyDetailsRequest,
				keyNumber: this.options.keyNumber
			};

			jQuery.ajax({
				type: 'POST',
				url: this.options.serviceUrl,
				data: params,
				dataFilter: $.msDataFilter,
				success: Function.createDelegate(this, this.loadDataRequestCompleteHandler),
				error: Function.createDelegate(this, this.loadDataRequestErrorHandler)
			});
		},

		loadDataRequestCompleteHandler: function (data, result) {
			if (typeof data != undefined) {
				var deptName = $('#deptName', this.content);
				var buttonLabel = $('#buttonLabel', this.content);
				var defaultPrice = $('#defaultPrice', this.content);
				var colors = $('#colorContainer', this.content);
				var taxRates = $('#taxRateContainer', this.content);
				var discountValue = $('#discountValue', this.content);

				deptName.val(data.DeptName);
				buttonLabel.val(data.ButtonLabel);


				colors.html(data.ColorHTML);
				taxRates.html(data.TaxRateHTML);
				UpdateSelectCss();

				$('input[name=radio_color]', this.content).click(Function.createDelegate(this, this.colorChanged));
				$('input[name=keySelector]', this.content).change(Function.createDelegate(this, this.keyTypeChangedHandler));
				$('input[name=valuePercentSelector]', this.content).click(Function.createDelegate(this, this.valueTypeChangedHandler));

				if (data.KeyType == '4') {
					$('#deptKeyList').hide();
					$('#discountSelector').attr('checked', 'checked');
					discountValue.val(data.DefaultPrice);
				}
				else {
					$('#discountKeyList').hide();
					$('#deptSelector').attr('checked', 'checked');
					defaultPrice.val(data.DefaultPrice);
				}

				if (data.IsPercent === 'True') {
					$('#percentSelector').attr('checked', 'checked');
				}
				else {
					$('#dollarSelector').attr('checked', 'checked');
				}

				this.valueTypeChangedHandler(null);
			}
		},

		loadDataRequestErrorHandler: function (response, result) {
			$.log('WARN', response.responseText);
			this.popup.hide();
			alert('Session has been expired. Please refresh the page.')
		},

		defaults: {
			serviceUrl: '',
			keyDetailsRequest: 'KeyDetails',
			keyUpdateRequest: 'KeyUpdate',
			templateUrl: ''
		}
	};

	$.fn.keyCustomization = function (options) {
		$(this).each(function () {
			new keyCustomization(this, options);
		});
	};
})(jQuery);


(function($) {

    incompleteKeypad = function(selector, options) {
        this.content = null;
        this.popup = null;
        this.options = $.extend({}, this.defaults, options);
        this.init();
    };

    incompleteKeypad.prototype = {
        init: function() {
            this.showIncompleteKeypadPopup();
        },

        showIncompleteKeypadPopup: function() {
            if (!this.content) {
                this.createContent();
            }
            this.initializeComponent();
            this.popup = this.createIncompleteKeypadPopup();
        },

        initializeComponent: function() {
            $('#noBtn', this.content).click(Function.createDelegate(this, this.nextStepHandler));
            $('#cancelBtn', this.content).click(Function.createDelegate(this, this.nextStepHandler));
            $('#yesBtn', this.content).click(Function.createDelegate(this, this.yesBtnHandler));
            $('#saveBtn', this.content).click(Function.createDelegate(this, this.saveBtnHandler));
        },

        nextStepHandler: function() {
            window.location = this.options.nextPageUrl;
        },

        saveBtnHandler: function() {
            var result = new StringBuilder();
            for (var i = 1; i <= 6; i++) {
                var price = $('#price_' + i);
                var color = $('#color_' + i);
                var rate = $('#rate_' + i);
                if (price[0]) {
                    var priceVal = price.val() ? price.val() : 0;
                    if (rate[0]) {
                        result.appendFormat('price_{0}={1}&color_{0}={2}&rate_{0}={3};', new Array(i, priceVal, color.val(), rate.val()));
                    }
                    else {
                        result.appendFormat('price_{0}={1}&color_{0}={2};', new Array(i, priceVal, color.val()));
                    }
                } else { break; }
            }

            params = {
                request: this.options.saveDataRequest,
                saveData: result.toString()
            };

            jQuery.ajax({
                type: 'POST',
                url: this.options.serviceUrl,
                data: params,
                dataFilter: $.msDataFilter,
                success: Function.createDelegate(this, this.saveDataRequestCompleteHandler),
                error: Function.createDelegate(this, this.saveDataRequestErrorHandler)
            });
        },

        saveDataRequestCompleteHandler: function(data, result) {
            if (typeof data != undefined) {
                if (data.IsSuccess) {
                    eval(data.UpdateKeypadScript);
                    this.popup.hide();
                }
                else {
                    this.showSaveDataRequestErrorMessage(data.ErrorMessage);
                }
            }
        },

        showSaveDataRequestErrorMessage: function(message) {
            $('form').messageBox(null, {
                messageType: 'Error',
                top: 10,
                width: 350,
                autoClose: true,
				containerClassName: 'popup-window ontop',
                title: "One or more errors have been detected",
                modal: false
            },
			$.generateList, { list: [message] });
        },

        saveDataRequestErrorHandler: function() {
            $.log('WARN', response.responseText);
            this.popup.hide();
            alert('Some errors was occured. Please try again later.');
        },

        yesBtnHandler: function() {
            $('#yesnoArea', this.content).css('display', 'none');
            $('#keysArea', this.content).css('display', '');
            this.remainKeysLoadData();
        },

        remainKeysLoadData: function() {
            params = {
                request: this.options.loadDataRequest
            };

            jQuery.ajax({
                type: 'POST',
                url: this.options.serviceUrl,
                data: params,
                dataFilter: $.msDataFilter,
                success: Function.createDelegate(this, this.loadDataRequestCompleteHandler),
                error: Function.createDelegate(this, this.loadDataRequestErrorHandler)
            });
        },

        loadDataRequestCompleteHandler: function(data, result) {
            if (typeof data != undefined) {
                var keysForm = $('#keysForm', this.content);
                keysForm.html(data);
                if (this.options.afterLoadDataHandler != null) {
                    this.options.afterLoadDataHandler();                
                }
            }
        },

        loadDataRequestErrorHandler: function(response, result) {
            $.log('WARN', response.responseText);
            this.popup.hide();
            alert('Session has been expired. Please refresh the page.')
        },

        createContent: function() {
            this.content = $.create('div', {});
            this.content.setTemplateURL(this.options.templateUrl, null, { filter_data: false });
            this.content.processTemplate(null);
        },

        createIncompleteKeypadPopup: function() {
            return $('form').messageBox(null, {
                messageType: '',
                contentClassName: '',
                title: 'Fill other buttons?',
                width: 500,
                top: 150,
                modal: true,
                autoClose: false,
                innerRound: 0
            }, this.content);
        },

        defaults: {
            serviceUrl: '',
            templateUrl: '',
            loadDataRequest: 'LoadData',
            saveDataRequest: 'SaveData',
            afterLoadDataHandler: null
        }
    };

    $.fn.incompleteKeypad = function(options) {
        $(this).each(function() {
            new incompleteKeypad(this, options);
        });
    };
})(jQuery);

(function($) {

	clearKeypad = function(selector, options) {
		this.content = null;
		this.popup = null;
		this.options = $.extend({}, this.defaults, options);
		this.init();
	};

	clearKeypad.prototype = {
		init: function() {
			this.showIncompleteKeypadPopup();
		},

		showIncompleteKeypadPopup: function() {
			if (!this.content) {
				this.createContent();
			}
			this.initializeComponent();
			this.popup = this.createClearKeypadPopup();
		},

		initializeComponent: function() {
			$('#noBtn', this.content).click(Function.createDelegate(this, this.nextStepHandler));
			$('#yesBtn', this.content).click(Function.createDelegate(this, this.yesBtnHandler));
		},

		nextStepHandler: function() {
			this.popup.hide();
		},

		yesBtnHandler: function() {
			params = {
				request: this.options.clearDataRequest
			};

			$('div[id^=key_]').parent().parent().find('li.assigned').removeClass('assigned');
			$('div[id^=key_]').parent().parent().find('li.ui-draggable').removeClass('ui-draggable');

			jQuery.ajax({
				type: 'POST',
				url: this.options.serviceUrl,
				data: params,
				dataFilter: $.msDataFilter,
				success: Function.createDelegate(this, this.clearDataRequestCompleteHandler),
				error: Function.createDelegate(this, this.clearDataRequestErrorHandler)
			});
		},

		clearDataRequestCompleteHandler: function(data, result) {
			if (typeof data != undefined) {
				if (data.IsSuccess) {
					eval(data.UpdateKeypadScript);
					$('div[id^=key_]').parent().parent().find('li').draggable('disable');
					$('div[id^=key_]').parent().parent().find('li.assigned').draggable('enable');
					this.popup.hide();
				}
				else {
					this.showClearDataRequestErrorMessage(data.ErrorMessage);
				}
			}
		},

		showClearDataRequestErrorMessage: function(message) {
			$('form').messageBox(null, {
				messageType: 'Error',
				top: 10,
				width: 350,
				autoClose: true,
				containerClassName: 'popup-window ontop',
				title: "One or more errors have been detected",
				modal: false
			},
			$.generateList, { list: [message] });
		},

		clearDataRequestErrorHandler: function() {
			$.log('WARN', response.responseText);
			this.popup.hide();
			alert('Some errors was occured. Please try again later.');
		},

		createContent: function() {
			this.content = $.create('div', {});
			this.content.setTemplateURL(this.options.templateUrl, null, { filter_data: false });
			this.content.processTemplate(null);
		},

		createClearKeypadPopup: function() {
			return $('form').messageBox(null, {
				messageType: '',
				contentClassName: '',
				title: 'Clear buttons?',
				width: 400,
				top: 150,
				modal: true,
				autoClose: false,
				innerRound: 0
			}, this.content);
		},

		defaults: {
			serviceUrl: '',
			clearDataRequest: 'ClearData'
		}
	};

	$.fn.clearKeypad = function(options) {
		$(this).each(function() {
			new clearKeypad(this, options);
		});
	};
})(jQuery);
