/*******************************************************************************
 * <pre>
 * SUMMARY
 * 
 * General function
 * ****************
 * null2Empty
 * emptySelect
 * loadSelect
 * formFieldValue
 * 
 * Polopoly Plugin
 * ***********
 * polopolyDatepicker 
 * polopolyDialog
 * polopolyGoto
 * 
 * Form Validation
 * ************
 * notAllowNegative
 * requiredSelect
 * 
 * MessageBox
 * ************
 * messageBox.alert(msg)
 * messageBox.info(msg)
 * messageBox.confirmYesNoCancel(msg, yesFunc, noFunc, cancelFunc)
 * messageBox.confirm(msg, yesFunc, noFunc)
 * 
 * 
 * </pre>
 ******************************************************************************/
(function($) { // hide the namespace
	/* * * * * * * * * * * * * * * * * * * * * * * * * 
	 * Global default setting - start
	 * * * * * * * * * * * * * * * * * * * * * * * * */
	// overide the datepicker default setting.
	$.datepicker.setDefaults( {
		dateFormat : 'dd/mm/yy',
		changeMonth : true,
		changeYear : true,
		// showButtonPanel: true,
		yearRange : '-100:+50'
	});
	
	/* * * * * * * * * * * * * * * * * * * * * * * * * 
	 * Global default setting - END
	 * * * * * * * * * * * * * * * * * * * * * * * * */

	/* * * * * * * * * * * * * * * * * * * * * * * * * 
	 * General Function - START
	 * * * * * * * * * * * * * * * * * * * * * * * * */
	$.fn.null2Empty = function(text) {
		if (text == null) {
			return "";
		} else {
			return $.trim(text);
		}
	};
	
	$.fn.emptySelect = function() {
		return this.each(function() {
			if (this.tagName == 'SELECT')
				this.options.length = 0;
		});
	}

	$.fn.loadSelect = function(json, options) {
		var defaults = {
	            disableClass : null,
	            enableClass : null
			};
		
		// Extend our default options with those provided.
		var opts = $.extend(defaults, options);
		// Our plugin implementation code goes here.
		
		return this.each(
				function() {
					var $this = $(this);
					
					if (this.tagName == 'SELECT') {
						// original value
						var origValue = $this.val();
						
						$this.emptySelect();
						
						var selectElement = this;
						
						$.each(json, function(index, optionData) {
							var option = new Option(optionData.value,
									optionData.key);
							if ($.browser.msie) {
								selectElement.add(option);
							} else {
								selectElement.add(option, null);
							}
						});
						
						var ind = $this.attr("selectedIndex");
						if (ind == -1) {
							$this.attr("disabled", true);
							$this.emptySelect();
							if(opts.enableClass!=null){
								$this.removeClass(opts.enableClass);
							}
							if(opts.disableClass!=null){
								$this.addClass(opts.disableClass);
							}
						}else{
							$this.removeAttr("disabled");
							
							// if the options has origin value, set value
							if($("option[value=" + origValue + "]", $this).length){
								$this.val(origValue);
							}
							if(opts.enableClass!=null){
								$this.addClass(opts.enableClass);
							}
							if(opts.disableClass!=null){
								$this.removeClass(opts.disableClass);
							}
						}
					}
				});
	}
	
	/**
	 * Return in array of [fieldName, value].
	 * NOTE : fieldName is name for field and not id for field.
	 * Example, return in [
	 * 	['username', 'kamhon'], ['user.username','eng']
	 * ]
	 */
	$.fn.formFieldValue = function(successful){
		if (typeof successful == 'undefined') successful = true;
		// from jquery.form.js
		var result = this.fieldSerialize(successful);
		var ss = result.split("&");
		
		var arr = new Array();
		if(ss.length){
			for(i=0; i<ss.length; i++){
				//arr[i] = ss[i].split("=");
				arr.push(ss[i].split("="));
			}
		}
		return arr;
	}

	/* * * * * * * * * * * * * * * * * * * * * * * * * 
	 * General Function - END
	 * * * * * * * * * * * * * * * * * * * * * * * * */

	/* * * * * * * * * * * * * * * * * * * * * * * * * 
	 * Polopoly plugin - start
	 * * * * * * * * * * * * * * * * * * * * * * * * */
	$.fn.polopolyDatepicker = function(options) {
        var defaults4Datepicker = {
            onSelect : function(dateText, inst) {
				// validate the input
        		if(!typeof $(this).valid == 'undefined')
        			$(this).valid();
            }
        };

		var defaults = {
			mask : "99/99/9999"
		};
		// Extend our default options with those provided.
		var opts4Datepicker = $.extend(defaults4Datepicker, options);
		var opts = $.extend(defaults, options);
		// Our plugin implementation code goes here.
		this.datepicker(opts4Datepicker).mask(opts.mask, opts);
		return this;
	};

	$.fn.polopolyDialog = function(options) {
		var defaults = {
			bgiframe : true,
			modal : true,
			autoOpen : false,
			width : 450,
			position : [ 'center', 'top' ]
		};
		// Extend our default options with those provided.
		var opts = $.extend(defaults, options);
		// Our plugin implementation code goes here.
		this.dialog(opts);
		return this;
	};
    
    $.fn.polopolyGoto = function(url, options) {
        var defaults = {
            confirm : false
		};
		// Extend our default options with those provided.
		var opts = $.extend(defaults, options);
		// Our plugin implementation code goes here.

        this.click(function(event){
            if(opts.confirm){
                alert("still not implemented yet!!");
            }else{
                window.location = url;
            }
        });
        return this;
    }
    
	/* * * * * * * * * * * * * * * * * * * * * * * * * 
	 * polopoly plugin - end
	 * * * * * * * * * * * * * * * * * * * * * * * * */

	/* * * * * * * * * * * * * * * * * * * * * * * * * 
	 * Form Validation - Start
	 * * * * * * * * * * * * * * * * * * * * * * * * */

	// this rules used for numeric field which not allow -ve value.
	$.validator.addMethod("notAllowNegative", function(value, element, param) {
		return this.optional(element)
				|| /^(?:\d+|\d{1,3}(?:,\d{3})+)(?:\.\d+)?$/.test(value);
	}, 'Please enter positive amount');

	// this rules used for select tag in Struts2 (<s:select/>) because default
	// selection for <s:select /> is index -1.
	$.validator.addMethod("requiredSelect", function(value, element, param) {
		return this.optional(element)
				|| /^(?:\d+|\d{1,3}(?:,\d{3})+)(?:\.\d+)?$/.test(value);
	}, 'This field is required');

	// this rules used for check special character in text field.
	$.validator.addMethod("notAllowSpecialCharacter", function(value, element,
			param) {
		return this.optional(element) || /^(\+)?(\w+)(\w+)?$/.test(value);
	}, 'Special Character not accept');

	/* * * * * * * * * * * * * * * * * * * * * * * * * 
	 * Form Validation - End
	 * * * * * * * * * * * * * * * * * * * * * * * * */
})(jQuery);


if (messageBox) throw("Initialized twice");
var messageBox = {};
messageBox.alert = function(msg){
	
	// if not defined
	if(!jQuery("#messageBox_alert").length){
		var s = "<div id='messageBox_alertModal'>\n<div class='ui-widget'>\n<div class='ui-state-error ui-corner-all' style='padding: 0 .7em;'>"
			+ "<p><span class='ui-icon ui-icon-alert' style='float: left; margin-right: .3em;'></span>"
			+ "<span id='messageBox_alert'></span></p>"
			+ "\n</div>\n</div>\n</div>";
		
		jQuery(s).appendTo("body");
		
		jQuery("#messageBox_alertModal").polopolyDialog({
			title:"Alert",
			// position : 'center',
			buttons:{
				"OK" : function(){
					jQuery(this).dialog('close');
				}
			}
		});
	}
	
	jQuery("#messageBox_alert").html(msg);
	jQuery("#messageBox_alertModal").dialog('open');
};

messageBox.info = function(msg){
	
	// if not defined
	if(!jQuery("#messageBox_info").length){
		var s = "<div id='messageBox_infoModal'>\n<div class='ui-widget'>\n<div class='ui-widget-content ui-corner-all' style='padding: 0 .7em;'>"
			+ "<p><span class='ui-icon ui-icon-info' style='float: left; margin-right: .3em;'></span>"
			+ "<span id='messageBox_info'></span></p>"
			+ "\n</div>\n</div>\n</div>";
		
		jQuery(s).appendTo("body");
		
		jQuery("#messageBox_infoModal").polopolyDialog({
			title:"Information",
			// position : 'center',
			buttons:{
				"OK" : function(){
					jQuery(this).dialog('close');
				}
			}
		});
	}
	
	jQuery("#messageBox_info").html(msg);
	jQuery("#messageBox_infoModal").dialog('open');
};

messageBox.confirmYesNoCancel = function(msg, yesFunc, noFunc, cancelFunc){
	var _isBtnClick = false;
	var _confirm = {};
	
	_confirm.yesFunc = function(){};
	_confirm.noFunc = function(){};
	_confirm.cancelFunc = function(){};
	
	if(typeof yesFunc == 'function'){
		_confirm.yesFunc = yesFunc;
	}
	
	if(typeof noFunc == 'function'){
		_confirm.noFunc = noFunc;
	}
	
	if(typeof cancelFunc == 'function'){
		_confirm.cancelFunc = cancelFunc;
	}
	
	// if not defined
	if(!jQuery("#messageBox_confirmYesNoCancel").length){
		var s = "<div id='messageBox_confirmYesNoCancelModal'>\n<div class='ui-widget'>\n<div class='ui-widget-content ui-corner-all' style='padding: 0 .7em;'>"
			+ "<p><span class='ui-icon ui-icon-info' style='float: left; margin-right: .3em;'></span>"
			+ "<span id='messageBox_confirmYesNoCancel'></span></p>"
			+ "\n</div>\n</div>\n</div>";
		
		jQuery(s).appendTo("body");
		
		jQuery("#messageBox_confirmYesNoCancelModal").polopolyDialog({
			title:"Confirmation",
			// position : 'center',
			buttons:{
				"Cancel" : function(){
					jQuery(this).dialog('close');
				},
				"No" : function(){
					jQuery(this).dialog('close');
				},
				"Yes" : function(){
					jQuery(this).dialog('close');
				}
			}
		});
	}
	
	jQuery("#messageBox_confirmYesNoCancel").html(msg);
	
	jQuery("#messageBox_confirmYesNoCancelModal").dialog('option', 'buttons', {
			"Cancel" : function(){
				_confirm.cancelFunc();
				_isBtnClick = true;
				jQuery(this).dialog('close');
			},
			"No" : function(){
				_confirm.noFunc();
				_isBtnClick = true;
				jQuery(this).dialog('close');
			},
			"Yes" : function(){
				_confirm.yesFunc();
				_isBtnClick = true;
				jQuery(this).dialog('close');
			}
		}
	);
	jQuery("#messageBox_confirmYesNoCancelModal").dialog('option', 'close',function(event, ui){
		if(!_isBtnClick)
			_confirm.cancelFunc();
	});
	
	jQuery("#messageBox_confirmYesNoCancelModal").dialog('open');
}

messageBox.confirm = function(msg, yesFunc, noFunc){
	var _isBtnClick = false;
	var _confirm = {};
	
	_confirm.yesFunc = function(){};
	_confirm.noFunc = function(){};
	_confirm.cancelFunc = function(){};
	
	if(typeof yesFunc == 'function'){
		_confirm.yesFunc = yesFunc;
	}
	
	if(typeof noFunc == 'function'){
		_confirm.noFunc = noFunc;
	}
	
	if(typeof cancelFunc == 'function'){
		_confirm.cancelFunc = cancelFunc;
	}
	
	// if not defined
	if(!jQuery("#messageBox_confirm").length){
		var s = "<div id='messageBox_confirmModal'>\n<div class='ui-widget'>\n<div class='ui-widget-content ui-corner-all' style='padding: 0 .7em;'>"
			+ "<p><span class='ui-icon ui-icon-info' style='float: left; margin-right: .3em;'></span>"
			+ "<span id='messageBox_confirm'></span></p>"
			+ "\n</div>\n</div>\n</div>";
		
		jQuery(s).appendTo("body");
		
		jQuery("#messageBox_confirmModal").polopolyDialog({
			title:"Confirmation",
			// position : 'center',
			buttons:{
				"No" : function(){
					jQuery(this).dialog('close');
				},
				"Yes" : function(){
					jQuery(this).dialog('close');
				}
			}
		});
	}
	
	jQuery("#messageBox_confirm").html(msg);
	
	jQuery("#messageBox_confirmModal").dialog('option', 'buttons', {
			"No" : function(){
				_confirm.noFunc();
				_isBtnClick = true;
				jQuery(this).dialog('close');
			},
			"Yes" : function(){
				_confirm.yesFunc();
				_isBtnClick = true;
				jQuery(this).dialog('close');
			}
		}
	);
	jQuery("#messageBox_confirmModal").dialog('option', 'close',function(event, ui){
		if(!_isBtnClick)
			_confirm.noFunc();
	});
	
	jQuery("#messageBox_confirmModal").dialog('open');
}

function jq(myid) { 
	return '#' + myid.replace(/(:|\.)/g,'\\$1');
}
