/**
 * 
 * @fileOverview  WHL plugins
 *  
 * @author WHL Member
 */
(function($){
    $.fn.extend({
        /**
         * Menu plugin, just apply for IE6
         */
        menu: function() {
            if ($.browser.msie && $.browser.version == '6.0') {
                return this.each(function(){
                    $(this).find('LI').each(function() {
                        if(this.lastChild.tagName=="UL"){
                            this.onmouseover=function() { 
                               $(this.lastChild).show();
                            };
                            this.onmouseout=function() {
                               $(this.lastChild).hide();
                            };
                        }
                    });
                });
            }
        },
        /**
         * Check required field
         * 
         * @returns {Boolean}
         */
        isBlank: function() {
            var value = $.trim(this.val());
            if (value == '' || value == '-1') {
                return false;
            }
            return true;
        },
        isChecked: function() {
            if (this.get(0).checked) return true;
            return false;
        },
        /**
         * Check valid email
         * 
         * @returns {Boolean}
         */
        isEmail: function() {
            var val = $.trim(this.val());
            if (val == '') return true;
            else return (val.search(/^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]{2,6}$/) == -1) ? false : true ;
        },
		/**
         * Check valid URL
         * 
         * @returns {Boolean}
         */
		isUrl: function() {  
      		var val = $.trim(this.val());
      		if (val == '') return true;
      		else return (val.search(/^(http|https):\/\/(([A-Z0-9][A-Z0-9_-]*)(\.[A-Z0-9][A-Z0-9_-]*)+)(:(\d+))?(\/)?/i) == -1) ? false : true ;
     	},
     	/**
     	 * Check valid domain www.xxx.xxx type.
     	 */
     	isDomain: function() {
     	   var val = $.trim(this.val());
           if (val == '') return true;
           else return (val.search(/^[A-Z0-9_-]*(\.[A-Z0-9_-]*)+/i) == -1) ? false : true ;
     	},
     	/**
     	 * CHeck the length of textbox, length must greater than the min value.
     	 * 
     	 * @param {Number} min Min length
     	 */
     	gtLength: function(min) {
     	   var val = $.trim(this.val());
           if (val == '') return true;
           else return (val.length > min);
     	},
        /**
         * Compare with other element date. (greater than : gt)
         * 
         * @param {String} elmId The element id that contains date to compare 
         */
        gtDate: function(elmId, equal) {
            equal = equal || false;
            if (equal) {
                return (Date.compareDate2(this.val(), $(elmId).val()) >= 0);
            }
            return (Date.compareDate2(this.val(), $(elmId).val()) > 0);
        },
        /**
         * Compare with other element date. (less than : gt)
         * 
         * @param {String} elmId The element id that contains date to compare 
         */
        ltDate: function(elmId, equal) {
            equal = equal || false;
            if (equal) {
                return (Date.compareDate2(this.val(), $(elmId).val()) <= 0);
            }
            return (Date.compareDate2(this.val(), $(elmId).val()) < 0);
        },
        /**
         * Compare with other element date. (less than : gt)
         * 
         * @param {String} dateVal The comparative date value 
         */
        ltDate2: function(dateVal, equal) {
            equal = equal || false;
            if (equal) {
                return (Date.compareDate2(this.val(), dateVal) <= 0);
            }
            return (Date.compareDate2(this.val(), dateVal) < 0);
        },
        /**
         * Compare with other element (Equal: eq)
         * 
         * @param {String} elmId
         * @returns {Boolean}
         */
        eqString: function(elmId) {
            return this.val().compare($(elmId).val());
        },
        /**
         * Compare with other element (greater than: gt)
         * 
         * @param {Number} compareValue Compare value
         * @param {Boolean} eq greater than or equal
         * @returns {Boolean}
         */
        gtNumber: function(compareValue, eq) {
            eq = eq || false;
            var valid = (Number.compareFloat(this.val(), compareValue) > 0);
            if (!valid && eq) {
                valid = (Number.compareFloat(this.val(), compareValue) == 0);
            }
            return valid;
        },
        /**
         * Compare with other element (smaller than: gt)
         * 
         * @param {Number} compareValue Compare value
         * @param {Boolean} eq smaller than or equal
         * @returns {Boolean}
         */
        stNumber: function(compareValue, eq) {
            eq = eq || false;
            var valid = (Number.compareFloat(this.val(), compareValue) < 0);
            if (!valid && eq) {
                valid = (Number.compareFloat(this.val(), compareValue) == 0);
            }
            return valid;
        },
        /**
         * Check the positive number
         * 
         * @returns {Boolean}
         */
        isPositiveNumber: function() {
            return (parseInt(this.val()) > 0);
        },
        /**
         * Check numeric value
         * 
         * @returns {Boolean}
         */
        isOnlyNumeric: function() {
            return ($.trim(this.val()).search(/^\d*(\.\d+)?$/) == -1) ? false : true ;
        },
        /**
         * Check integer value
         * 
         * @returns {Boolean}
         */
         isValidInteger: function() {
            return ($.trim(this.val()).search(/^((\+|-)\d)?\d*$/) == -1) ? false : true ;
         },
         /**
         * Check float value
         * 
         * @returns {Boolean}
         */
         isValidFloat: function() {
             return ($.trim(this.val()).search(/^((\+|-)\d)?\d*(\.\d+)?$/) == -1) ? false : true ;
         },
         /**
         * Check alphabetic value
         * 
         * @returns {Boolean}
         */
         isOnlyAlphabetic: function() {
             return ($.trim(this.val()).search(/[a-z ]/i) == -1) ? false : true ;
         },
         /**
         * Check match between 2 values
         * 
         * @returns {Boolean}
         */
         isMatch: function(comparedId) {
             return $('#'+comparedId).val()==this.val() ? true : false ;
         },
         /**
          * Check the element does exist
          * 
          * @returns {Boolean} True element exists, otherwise not exist
          */
         isExist: function() {
             return (this.length > 0);
         },
         /**
          * Test input data have to be number integer
          * 
          * @returns {Boolean}
          */
         forceNumber: function() {
             return this.each(function(){
                 $(this).keypress(function(event){
                     var arrowCode = 0;
                     var keyCode = 0;
                     if ($.browser.msie) {       
                         keyCode = event.keyCode;
                     } else {
                         keyCode = event.which;
                         arrowCode = event.keyCode;
                     }
                     if (37<=arrowCode && arrowCode<=40 ) return true;
                     if (8==arrowCode || arrowCode==46 || arrowCode==35|| arrowCode==36 || arrowCode == 9) return true;
                     
                     if (48<=keyCode && keyCode<=57 || (keyCode==13)) return true;
                     return false;
                 });
             });
         },
         /**
          * Test input data have to be float number
          * 
          * @returns {Boolean}
          */
         forceFloat: function() {
             return this.each(function(){
                 $(this).keypress(function(event){
                     var arrowCode = 0;
                     var keyCode = 0;
                     if ($.browser.msie) {       
                         keyCode = event.keyCode;
                     } else {
                         keyCode = event.which;
                         arrowCode = event.keyCode;
                     }
                     if (37<=arrowCode && arrowCode<=40 ) return true;
                     if (8==arrowCode || arrowCode==46 || arrowCode==35|| arrowCode==36 || arrowCode == 9) return true;
                     
                     if ((48<=keyCode && keyCode<=57) || keyCode == 46 || keyCode == 118) return true;
                     return false;
                 });
             });
         },
         /**
          * allow only [0-9][a-z][A-Z][.-_]
          * 
          * @returns {void}
          */
         forceAlphaNumber: function() {
			 return this.each(function(){
                 $(this).keypress(function(event){
                     var arrowCode = 0;
                     var keyCode = 0;
                     if ($.browser.msie) {       
                         keyCode = event.keyCode;
                     } else {
                         keyCode = event.which;
                         arrowCode = event.keyCode;
                     }
                     if (37<=arrowCode && arrowCode<=40 ) return true;
                     if (8==arrowCode || arrowCode==46 || arrowCode==35|| arrowCode==36 || arrowCode == 9) return true;
                     
                     if ((48 <= keyCode && keyCode <= 57) || (keyCode >= 65 && keyCode <= 90) || (keyCode >= 97 && keyCode <= 122) || (keyCode == 13) || (keyCode == 8) || (keyCode == 9)) {
                         return true;
                     }
                     return false;
                 });
             });             
         },
         /**
          * Remove the validator error message
          * 
          * @returns {void}
          */
         removeError: function() {
             return this.each(function() {
                 $(this).removeClass('error').html('');
             });
         },
         /**
          * Register hover event for image button
          * 
          * @returns {void}
          */
         btnHover: function() {
             return this.each(function() {
                 $(this).hover(function() {
                     this.src = this.src.replace(/(.gif|.jpeg)$/gi, '_on$1');
                 }, function() {
                     this.src = this.src.replace(/_on/g, '');
                 });
             });
         },
         /**
          * Toolip plugins, reference to jquery tooltip
          * 
          * @param {Object} setting Setting for the tooltip
          * @returns {Object} jquery objects 
          */
         tooltip: function(setting) {
             setting = Object.extend({  ajaxUrl: null, 
                                        title: '', 
                                        click: false, 
                                        prefixCont: null, 
                                        callback: null, 
                                        left: 15, 
                                        top: 15, 
                                        positionLeft: false, 
                                        param: {},
                                        width: 'auto',
                                        height: 'auto',
                                        actionDefault: false}, setting);
             var tooltip = $('#tooltip');
             if (!tooltip.isExist()) {
                 tooltip = '<div id="tooltip">'+
                                 '<div class="header">' +
                                     '<span id="tooltip-title"></span>' +
                                     '<span id="tooltip-close" class="ui-icon ui-icon-close" style="cursor:pointer"></span><br class="clear"/>' +
                                 '</div>' +
                                 '<p id="tooltip-cont" class="cont"></p>'+
                             '</div>';
                 tooltip = $(tooltip).appendTo(document.body);
             }
             tooltip.cont = $('#tooltip-cont', tooltip);
             tooltip.title = $('#tooltip-title', tooltip);
             tooltip.hide();
             // Show tooltip
             var show = function(event) {
                 var left = tooltip.offsetLeft;
                 var top = tooltip.offsetTop;
                 left = event.pageX + setting.left;
                 top = event.pageY + setting.top;
                 var right='auto';
                 if (setting.positionLeft) {
                     right = $(window).width() - left;
                     left = 'auto';
                 }
                 $(tooltip).css({left: left, right: right, top: top});
                 var viewPort = {
                     x: $(window).scrollLeft(),
                     y: $(window).scrollTop(),
                     cx: $(window).width(),
                     cy: $(window).height()
                 };
                 // check horizontal position
                 if (viewPort.x + viewPort.cx < tooltip.offsetLeft + tooltip.offsetWidth) {
                     left -= tooltip.offsetWidth + 20 + setting.left;
                     $(tooltip).css({left: left + 'px'});
                 }
                 // check vertical position
                 if (viewPort.y + viewPort.cy < tooltip.offsetTop + tooltip.offsetHeight) {
                     top -= tooltip.offsetHeight + 20 + setting.top;
                     $(tooltip).css({top: top + 'px'});
                 }
                 $(tooltip).show();
             };
             // Hide tooltip
             var hide = function(event) {
                 $(tooltip).hide();
             };
             return this.each(function() {
                 // Save data for each control
                 var title = '';
                 if (setting.title) title = setting.title;
                 else {
                     title = this.title;
                     $(this).removeAttr('title');
                 }
                 $(this).data('title', title);
                 $(this).data('click', setting.click);
                 $(this).data('width', setting.width);
                 var id = this.id.split('-');
                 id = id[id.length-1];
                 if (setting.ajaxUrl) {
                     // Ajax get content
                     var get = function() {
                         tooltip.cont.html(Message.loading);
                         $.get(  setting.ajaxUrl, 
                                 param, 
                                 function(data) {
                                     tooltip.cont.html(data);
                                 }, 'html');
                     };
                     if (setting.click) {
                         $(this).click(function(event) {
                             event.preventDefault();
                             tooltip.title.html($(this).data('title'));
                             show(event);
                             tooltip.draggable({handle: 'div', cancel: "p.ui-widget-header"});
                             $('#tooltip-close').click(hide.bindEvent(tooltip.get(0)));
                             get();
                         }.bindEvent(this));
                     } else {
                         $(this).mouseover(function(event) {
                             $('#tooltip-close').hide();
                             tooltip.title.html($(this).data('title'));
                             show(event);
                             get();
                         }.bindEvent(this)).mouseout(hide.bindEvent()).click(function(event) {
                             event.preventDefault();
                         });
                     }
                 } else {
                     // Get content
                     var cont = '';
                     if (setting.prefixCont) cont = $('#' + setting.prefixCont + '-' + id).html();
                     else {
                         if (this.title == '') return true;
                         cont = this.title;
                         $(this).removeAttr('title');
                         this.alt = '';
                     }
                     // If cont is empty, remove
                     if (cont == '') {
                         if (setting.prefixCont) $(this).remove();
                         return true;
                     }
					 if(setting.actionDefault){
						  $(this).mouseover(function(event) {
                             event.preventDefault();
                             tooltip.title.html($(this).data('title'));
                             tooltip.cont.html(cont);
                             show(event);
                             tooltip.draggable({handle: 'div', cancel: "p.ui-widget-header"});
                            $('#tooltip-close').hide();
                         }.bindEvent(this)).mouseout(hide.bindEvent());
						 return true;
					 }
                     // Add mouse over, mouse out and click event handler
                     if (setting.click) {
                         $(this).click(function(event) {
                             event.preventDefault();
                             tooltip.title.html($(this).data('title'));
                             tooltip.cont.html(cont);
                             show(event);
                             tooltip.draggable({handle: 'div', cancel: "p.ui-widget-header"});
                             $('#tooltip-close').show().click(hide.bindEvent(tooltip.get(0)));
                         }.bindEvent(this));
                     } else {
                         $(this).mouseover(function(event) {
                             tooltip.title.html($(this).data('title'));
                             tooltip.cont.html(cont);
                             // Re-width/height if needed
                             if (setting.width != 'auto') {
                                 tooltip.css('width', setting.width + 'px');
                             } else {
                                 tooltip.css('width', 'auto');
                             }
                             show(event);
                             $('#tooltip-close').hide();
                         }.bindEvent(this)).mouseout(hide.bindEvent()).click(function(event) {
                             event.preventDefault();
                         });
                     }
                 }
             });
         },
         loadService: function(url, option) {
             if (this.length == 0) return;
             var control = this;
             control.hide();
             option = option || {param: {}, after: true, removeLoader: true};
             option.param = option.param ? Object.createQueryString(option.param) : '';
             $.ajax({
                 type: 'get',
                 url: url + (option.param ? '&' + option.param : ''),
                 dataType: 'text',
                 success:  function(data) {
                     control.show();
                     if (data) {
                         if (option.after) control.after(data);
                         else control.html(data);
                         control.show();
                     } 
                     if (option.removeLoader) {
                         control.remove();
                     }
                 },
                 error: function(XMLHttpRequest, textStatus, errorThrown) {}
             });
         }
    });
})(jQuery);
