/**
 * Sales environment base functionality
 * @copyright Mekaia 2010
 */

var Sales = (function(){
	var _form = null;
	var _validation = null;
	
	/**
	 * handle request exceptions
	 * @param {Object} except
	 * @return void
	 */
	function _handleException(except){
		if(!except.data || !except.data.message){ return false; }
		alert(except.data.message);
	}
	
	/**
	 * build data object from serialized form data
	 * @param {Object} serialized
	 * @return {Object}
	 */
	function _buildDataArray(serialized){
		if(!serialized || serialized.length < 1){ return {}; }
		var data = {};
		
		// parse serialized data
		for(var i in serialized){
			var row = serialized[i];
			data[row.name] = row.value;
		}
		
		return data;
	}
	
	/**
	 * validate data
	 * @param {Object} data
	 * @param {Boolean} withMessages
	 * @return boolean
	 */
	function _validate(data, withMessages){
		if(!data || data.length < 1 || _validation === null){ return false; }
		var hasError = false;
		
		// validate data
		for(var i in _validation){
			var name = i;
			var rules = _validation[i];
			
			// validate required
			if(jQuery.inArray('required', rules) > -1){
				if(!data[name] || data[name].length < 1){
					hasError = true;
					continue;
				}
			}
			
			// validate email address
			if(jQuery.inArray('email', rules) > -1){
				if(!data[name] || /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/.test(data[name]) === false){
					hasError = true;
					continue;
				}
			}
		}
		
		if(hasError){
			alert('Palun kontrollige, et väljad oleksid õigesti täidetud!');
			return false;
		}
		
		// reset validation params
		_validation = null;
		return true;
	}
	
	/**
	 * post data to url 
	 * @param {String} url
	 * @param {Object} data
	 * @param {Object} callbacks
	 * @return void
	 */
	function _post(url, data, callbacks){
		if(!url || url.length < 1){ return false; }
		
		// build request url
		var exp = url.split('/');
		if(exp.length < 2){ exp[1] = 'index'; }
		url = EXTENSION_URL + 'Model/ControllerHandler.php?controller=' + exp[0] + '&action=' + exp[1];
			
		// execute before request callback
		if(typeof callbacks.onBeforeRequest === "function"){
			callbacks.onBeforeRequest();
		}
	
		// make the request
		jQuery.post(url, data, function(response){
			// handle exceptions
			if(response.error){
				_handleException(response);
				return;
			}
			
			// redirect
			if(response.redirect && response.redirect.length > 0){
				location.href = response.redirect;
				return;
			}
			
			// execute oncomplete callback
			if(typeof callbacks.onComplete === "function"){
				callbacks.onComplete(response);
			}
		}, 'json');
	
		// execute after request callback
		if(typeof callbacks.onAfterRequest === "function"){
			callbacks.onAfterRequest();
		}
	}
	
	return {
		/**
		 * get product price
		 * @return boolean
		 */
		getProductPrice: function(){
			// set validation parameters
			_validation = {
				'duration': ['required'],
				'product_code': ['required'],
				'product_qty': ['required']
			};
			
			// collect and validate data
			var data = {
				'duration': jQuery('#duration').val(),
				'product_code': jQuery('#product_code').val(),
				'product_qty': jQuery('#product_qty').val()
			};
			if(_validate(data)){
				_post('product/price', data, {
					// @todo: show/hide loader image
					'onBeforeRequest': function(){},
					'onAfterRequest': function(){},
					
					// inject price to content
					'onComplete': function(response){
						jQuery("#product_price").text(response.data.price + " EEK");
					}
				});
				return true;
			}
			return false;
		},
		
		/**
		 * get product price for enlargement
		 * @return boolean
		 */
		getProductPriceForEnlarge: function(){
			// set validation parameters
			_validation = {
				'duration': ['required'],
				'product_code': ['required'],
				'product_qty': ['required']
			};
			
			// collect and validate data
			var data = {
				'duration': jQuery('#duration').val(),
				'product_code': jQuery('#product_code').val(),
				'product_qty': jQuery('#product_qty').val()
			};
			if(_validate(data)){
				_post('product/price-enlarge', data, {
					// @todo: show/hide loader image
					'onBeforeRequest': function(){},
					'onAfterRequest': function(){},
					
					// inject price to content
					'onComplete': function(response){
						jQuery("#product_price").text(response.data.price + " EEK");
					}
				});
				return true;
			}
			return false;
		},
		
		/**
		 * register new license
		 * @return boolean
		 */
		registerNewLicense: function(){
			// set validation parameters
			_validation = {
				'register[email]': ['required', 'email'],
				'register[email2]': ['required', 'email'],
				'register[serial_number]': ['required'],
				'register[serial_number2]': ['required'],
				'register[client_name]': ['required'],
				'register[form_number]': ['required']
			};
			
			// collect and validate data
			var data = _buildDataArray(jQuery(':input[name^=register]').serializeArray());
			if(_validate(data)){
				_post('license/register-new', data, {
					// @todo: show/hide loader image
					'onBeforeRequest': function(){},
					'onAfterRequest': function(){},
					
					// update content
					'onComplete': function(response){
						if(!response.data){ return false; }
						jQuery('.content').html(response.data.html);
					}
				});
			}
		},
		
		/**
		 * post license order data
		 * @return boolean
		 */
		licenseOrder: function(){
			// set validation parameters
			_validation = {
				'order[update_type]': ['required'],
				'order[product_code]': ['required'],
				'order[product_qty]': ['required'],
				'order[duration]': ['required'],
				'order[email]': ['required', 'email']
			};
			
			// collect data and validate
			var data = _buildDataArray(jQuery(':input[name^=order]').serializeArray());
			if(_validate(data)){
				_post('sales/license-order', data, {
					// @todo: show/hide loader image
					'onBeforeRequest': function(){},
					'onAfterRequest': function(){},
					
					// update content
					'onComplete': function(response){
						if(!response.data){ return false; }
						jQuery('#license_order_content').html(response.data.html);
					}
				});
				return true;
			}
			
			return false;
		},
		
		/**
		 * renew license data
		 * @return boolean
		 */
		licenseRenew: function(){
			// set validation parameters
			_validation = {
				'order[current_username]': ['required'],
				'order[current_password]': ['required'],
			};
			
			// collect data and validate
			var data = _buildDataArray(jQuery(':input[name^=order]').serializeArray());
			if(_validate(data)){
				_post('sales/license-order', data, {
					// @todo: show/hide loader image
					'onBeforeRequest': function(){},
					'onAfterRequest': function(){},
					
					// update content
					'onComplete': function(response){
						if(!response.data){ return false; }
						jQuery('#license_order_content').html(response.data.html);
					}
				});
				return true;
			}
			
			return false;
		},
		
		/**
		 * pre-order license
		 * @return boolean
		 */
		licensePreOrder: function(){
			// set validation parameters
			_validation = {
				'order[update_type]': ['required'],
				'preview[product_code]': ['required'],
				'preview[product_qty]': ['required'],
				'preview[duration]': ['required'],
				'preview[email]': ['email', 'required']
			};
			
			// collect data and validate
			var data = _buildDataArray(jQuery(':input[name^=preview], :input[name^=order]').serializeArray());
			if(_validate(data)){
				_post('sales/license-pre-order', data, {
					// @todo: show/hide loader image
					'onBeforeRequest': function(){},
					'onAfterRequest': function(){},
					
					// update content
					'onComplete': function(response){
						if(!response.data){ return false; }
						jQuery('#license_order_content').html(response.data.html);
					}
				});
			}
			
			return false;
		},
		
		/**
		 * manage license
		 * @return boolean
		 */
		manageProductLicense: function(){
			// get discount type
			var discount = jQuery('input[name="order[discount_type]"]:checked').val();
			discount = discount ? discount : 'normal';
			
			// collect data and post
			var data = {
				'person': jQuery('input[name="order[user_type]"]').val(),
				'product_code': jQuery('#product_code').val(),
				'discount_type': discount
			};
			_post('sales/manage-product-license', data, {
				// @todo: show/hide loader image
				'onBeforeRequest': function(){},
				'onAfterRequest': function(){},
				
				// update content
				'onComplete': function(response){
					if(!response.data){ return false; }
					jQuery('#product_qty').html(response.data.licenses);
					jQuery('#duration').html(response.data.years);
					
					// get product price
					Sales.getProductPrice();
				}
			});
			
			return true;
		},
		
		/**
		 * resend license access to email address
		 * @param {String} address
		 * @return boolean
		 */
		resendLicenseAccess: function(address){
			// set validation parameters
			_validation = {
				'email': ['required', 'email']
			};
			
			// collect and validate data
			var data = {
				'email': address
			};
			if(_validate(data)){
				_post('license/resend-access', data, {
					// @todo: show/hide loader image
					'onBeforeRequest': function(){},
					'onAfterRequest': function(){}
				});
				return true;
			}
			
			return false;
		}
	}
})();
