﻿/********************************************************************
	created:	2009/09/30
	created:	30:9:2009   10:09
	filename: 	D:\MyWork\Swim.com\swim-frontend\jquery\jquery.ext.js		
	author:		phuc.pham	
	to do:		
*********************************************************************/

String.prototype.isZipCode = function(countryCode) {
    if (countryCode == 'USA' || countryCode == 'US') return this.isZipCodeUS();
    else if (countryCode == 'CAN' || countryCode == 'CA') return this.isZipCodeCA();
    else return false;
}

String.prototype.isZipCodeUS = function() {
    var m = this.match(/\d{5}\s*(-\s*\d{4})?/g);
    return (j$.trim(this) == '' || m == null) ? false : this == m[0];
}

String.prototype.isZipCodeCA = function() {
    var m = this.match(/[a-z]\d[a-z]\s*\d[a-z]\d/gi)[0];
    return (j$.trim(this) == '' || m == null) ? false : this == m[0];
}

String.prototype.endsWith = function(suffix) {
    return (this.substr(this.length - suffix.length) === suffix);
}

String.prototype.startsWith = function(prefix) {
    return (this.substr(0, prefix.length) === prefix);
}

String.prototype.breakString = function(limit){
    
    var temp = this.split(' ');
    for( var index = 0; index<temp.length; index ++){
        var str = temp[index];
        if( str.length >  limit  ){
            str = str.split('').join('<wbr/>'); // str.substring(0, limit) + '<wbr/>' + str.substring(limit).breakString(limit);            
        }
        
        temp[index] = str;
    }
    
    return temp.join(' ');
};

String.prototype.isUrl = function(){
			return /^(((https?|ftp):\/\/)|www\.)(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(\#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/i.test(this);
};

String.prototype.getValueByKey = function(key) {
    key = key.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
    var regexS = "[\\?&]" + key + "=([^&#]*)";
    var regex = new RegExp(regexS);
    var results = regex.exec(this || window.location.href);
    if (results == null)
        return "";
    else
        return decodeURIComponent(results[1].replace(/\+/g, " "));
};

String.prototype.format = function(){
	if( arguments.length < 1 )
		return this;
	
	var newthis = this;
	
	for( var index = 0; index < arguments.length; index ++ ){
		var str = '{'+ index +'}';
		
		newthis = newthis.split(str).join(arguments[index]);
	}
	
	return newthis;
};

String.prototype.getHostname = function() {
    var re = new RegExp('^(?:f|ht)tp(?:s)?\://([^/]+)', 'im');
    return this.match(re)[1].toString();
}

String.prototype.wrapLinkOverflow = function(limit) {
    var linkTemplate = '<a title="{0}" href="{0}" {2} target="_blank">{1}</a>';
    var temp = this.split(' ');
    var ret = [];
    var count = 0;
    var flagUrl = false;
    var flagText = false;
    var result = '';

    for (var index = 0; index < temp.length; index++) {
        var href = temp[index];
        var text = temp[index];

        if (href.isUrl()) {
            var noFol = "";
            var hostname = href.getHostname().toLowerCase();
            if (!(hostname == window.location.hostname.toLowerCase() || hostname.indexOf("isport.com") >= 0 || hostname.indexOf("isportalpha.com") >= 0)) {
                noFol = " rel=\"nofollow\"";
            }
            
            if (count + text.length > limit) {
                text = text.substring(0, limit - count);
                if (limit - count > 8)
                    ret.push(linkTemplate.format(href, text, noFol));
                else
                    ret.push(text);

                flagUrl = true;
                break;
            }
           
            ret.push(linkTemplate.format(href, text, noFol));
        }
        else {
            if (count + text.length > limit) {
                text = text.substring(0, limit - count);

                flagText = true;
            }

            ret.push(text);
        }

        count += text.length;
        limit--;
    }

    result = ret.join(' ');

    if (flagUrl || flagText) {
        var $ = jQuery; if ($) result = $.trim(result);

        if (flagText) {
            var index = result.lastIndexOf(' ');
            if (index > 0) result = result.substring(0, index);
        }

        result = result.concat('...');
    }

    return result;
}

String.prototype.wrapLink = function(){
    
    var linkTemplate = '<a href="{0}" target="_blank">{1}</a>';
    var temp = this.split(' ');
    
    for( var index = 0; index<temp.length; index ++){
        var href = temp[index].split('<wbr/>').join('');
        var text = temp[index];
        
        if(! href.isUrl() ){            
            continue;
        }
        
        temp[index] = linkTemplate.replace('{0}', href).replace('{1}', text);
    }
    
    return temp.join(' ');
};

String.prototype.casePascal = function(){
    var text = this;
    
    var array = text.split(' ');
    var index =  0;            
    
    for(; index < array.length; index++){
        if( array[index] == "" )
            continue;
            
        array[index] = array[index].substring(0, 1).toUpperCase() + array[index].substring(1, array[index].length).toLowerCase();
    }
    
    return array.join(' ');
};

String.prototype.isEmpty = function(value) {
    if (value == null) {
        return this == undefined || this == 'undefined' || this == '' || this == null;
    }
    else {
        return value == undefined || value == 'undefined' || value == '' || value == null;
    }
};

String.prototype.htmlEncode = function() {
    var value = this.toString();

    if (!window.jQuery) return value;
    return jQuery('<div/>').text(value).html();
};

String.prototype.htmlDecode = function() {
    var value = this.toString();

    if (!window.jQuery) return value;
    return jQuery('<div/>').html(value).text();
};

(function($) {
    $.extend($, {

        postJSW: function(url, data, callback, type, completeCallback) {
            var newdata = $.getJSONString(data);

            //return $.post(url, {data: newdata}, callback, type);

            if (callback == null)
                callback = function() { };

            if (completeCallback == null)
                completeCallback = function() { };

            return $.ajax({
                url: url,
                type: "post",
                data: ({ data: newdata }),
                dataType: type,
                success: callback,
                complete: completeCallback
            });
        },

        getJSONLength: function(json) {
            var count = 0;
            $.each(json, function(key, item) {
                count++;
            });

            return count;
        },

        getJSONString: function(json) {
            return $.json.encode(json);
        }

    });
})(jQuery);

(function($) {
    $.extend($.fn, {
        getCss: function(file) {
            j$("head").append("<link>");
            css = $("head").children(":last");
            css.attr({
                rel: "stylesheet",
                type: "text/css",
                href: file
            });
        }
    });
})(jQuery);


(function($) {
    $.extend($.fn, {
        getCursorPosition: function() {
            var pos = 0;
            var input = $(this).get(0);
            // IE Support
            if (document.selection) {
                input.focus();
                var sel = document.selection.createRange();
                var selLen = document.selection.createRange().text.length;
                sel.moveStart('character', -input.value.length);
                pos = sel.text.length - selLen;
            }
            // Firefox support
            else if (input.selectionStart || input.selectionStart == '0')
                pos = input.selectionStart;

            return pos;
        },
        
        disableTextSelect: function() {
            return this.each(function() {
                if ($.browser.mozilla) {//Firefox
                    $(this).css('MozUserSelect', 'none');
                } else if ($.browser.msie) {//IE
                    $(this).bind('selectstart', function() { return false; });
                } else {//Opera, etc.
                    $(this).mousedown(function() { return false; });
                }
            });
        },

        attrs: function(name) {
            var values = [];

            this.each(function() {
                values.push($(this).attr(name));
            });

            return values;
        },

        isEmpty: function(value) {
            //return this == 'undefined' || this == '' || this == null;
            if (value == null) {
                return this == undefined || this == 'undefined' || this == '' || this == null;
            }
            else {
                return value == undefined || value == 'undefined' || value == '' || value == null;
            }
        },

        radioValue: function() {

            var ret = "";

            this.each(function() {
                if ($(this).attr('type') == 'radio' && $(this).attr('checked'))
                    ret = $(this).val();
            });

            return ret;
        },

        extractFormValues: function(prefix) {
            var arr = [];

            this.each(function() {
                var ret = {};

                if (this.tagName && this.tagName.toLowerCase() == 'form') {

                    for (var i in this) {

                        var obj = this[i];

                        if (obj == null)
                            continue;

                        var objString = Object.prototype.toString.apply(obj);

                        //if( typeof(obj) == 'object' && $.isArray(obj) ){
                        if (objString === '[object NodeList]' || (obj.constructor && obj.constructor.toString() === '[object HTMLCollection]')) {
                            if (obj[0] && $(obj[0]).attr('type') == "radio" && $(obj).attr('name').toLowerCase().indexOf(prefix) == 0) {
                                ret[$(obj[0]).attr('name')] = $(obj).radioValue();
                            }
                            continue;
                        }
                        else if (obj.nodeType != 1) {
                            continue;
                        }

                        var name = $(obj).attr('name');

                        if (name && name.toLowerCase().indexOf(prefix) == 0) {
                            var type = $(obj).attr('type');
                            switch (type) {
                                case "text":
                                    ret[name] = $(obj).val();
                                    break;
                                case "checkbox":
                                    ret[name] = $(obj).attr('checked') ? "Y" : "N";
                                    break;
                                case "radio":
                                    if ($(obj).attr('checked'))
                                        ret[name] = $(obj).radioValue();
                                    else if (ret[name] == null)
                                        ret[name] = '';
                                    break;
                                default:
                                    if ($(obj).attr('tagName')) {
                                        var tag = $(obj).attr('tagName').toLowerCase();
                                        if (tag == 'select' || tag == 'textarea') {
                                            ret[name] = $(obj).val();
                                        }
                                    }

                                    break;
                            }
                        }
                    }

                    arr.push(ret);
                }

            });

            return arr.length == 1 ? arr[0] : arr;
        }
    });


})(jQuery); 

/**
 * labs_json Script by Giraldo Rosales.
 * Version 1.0
 * Visit www.liquidgear.net for documentation and updates.
 *
 *
 * Copyright (c) 2009 Nitrogen Design, Inc. All rights reserved.
 * 
 * Permission is hereby granted, free of charge, to any person
 * obtaining a copy of this software and associated documentation
 * files (the "Software"), to deal in the Software without
 * restriction, including without limitation the rights to use,
 * copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following
 * conditions:
 * 
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
 * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
 * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
 * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 * OTHER DEALINGS IN THE SOFTWARE.
 **/
 
/**
 * HOW TO USE
 * ==========
 * Encode:
 * var obj = {};
 * obj.name	= "Test JSON";
 * obj.type	= "test";
 * $.json.encode(obj); //output: {"name":"Test JSON", "type":"test"}
 * 
 * Decode:
 * $.json.decode({"name":"Test JSON", "type":"test"}); //output: object
 * 
 */

jQuery.json = {
    encode:function(value, replacer, space) {
		var i;
		gap = '';
		var indent = '';
		
		if (typeof space === 'number') {
			for (i = 0; i < space; i += 1) {
				indent += ' ';
			}
			
		} else if (typeof space === 'string') {
			indent = space;
		}
		
		rep = replacer;
		if (replacer && typeof replacer !== 'function' &&
				(typeof replacer !== 'object' ||
				 typeof replacer.length !== 'number')) {
			throw new Error('JSON.encode');
		}
		
		return this.str('', {'': value});
    },
    
    decode:function(text, reviver) {
		var j;
		var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g;
		
		function walk(holder, key) {
			var k, v, value = holder[key];
			
			if (value && typeof value === 'object') {
				for (k in value) {
					if (Object.hasOwnProperty.call(value, k)) {
						v = walk(value, k);
						if (v !== undefined) {
							value[k] = v;
						} else {
							delete value[k];
						}
					}
				}
			}
			return reviver.call(holder, key, value);
		}
		
		cx.lastIndex = 0;
		
		if (cx.test(text)) {
			text = text.replace(cx, function (a) {
				return '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
			});
		}
		
		if (/^[\],:{}\s]*$/.test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@').replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']').replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {
			j = eval('(' + text + ')');
			return typeof reviver === 'function' ? walk({'': j}, '') : j;
		}
		
		throw new SyntaxError('JSON.parse');
	},
	
    f:function(n) {
        return n < 10 ? '0' + n : n;
    },
	
	DateToJSON:function(key) {
		return this.getUTCFullYear() + '-' + this.f(this.getUTCMonth() + 1) + '-' + this.f(this.getUTCDate())      + 'T' + this.f(this.getUTCHours())     + ':' + this.f(this.getUTCMinutes())   + ':' + this.f(this.getUTCSeconds())   + 'Z';
	},
	
	StringToJSON:function(key) {
		return this.valueOf();
    },
    
    quote:function(string) {
        var meta = {'\b': '\\b','\t': '\\t','\n': '\\n','\f': '\\f','\r': '\\r','"' : '\\"','\\': '\\\\'};
        var escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g;
        
        escapable.lastIndex = 0;
        return escapable.test(string) ?
            '"' + string.replace(escapable, function (a) {
                var c = meta[a];
                return typeof c === 'string' ? c :
                    '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
            }) + '"' :
            '"' + string + '"';
    },
    
    str:function(key, holder) {
        var indent='', gap = '', i, k, v, length, mind = gap, partial, value = holder[key];
        
        if (value && typeof value === 'object') {
            switch((typeof value)) {
            	case 'date':
            		this.DateToJSON(key);
            		break;
            	default:
            		this.StringToJSON(key);
            		break;
            }
        }
        
        if (typeof rep === 'function') {
            value = rep.call(holder, key, value);
        }
        switch (typeof value) {
        	case 'string':
        	    return this.quote(value);
			case 'number':
	            return isFinite(value) ? String(value) : 'null';
			case 'boolean':
			case 'null':
	            return String(value);
	        case 'object':
				if (!value) {
					return 'null';
				}
				gap += indent;
				partial = [];
				
				if (Object.prototype.toString.apply(value) === '[object Array]') {
					length = value.length;
					
					for (i = 0; i < length; i += 1) {
						partial[i] = this.str(i, value) || 'null';
					}
	
					v = partial.length === 0 ? '[]' : gap ? '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']' : '[' + partial.join(',') + ']';
					gap = mind;
					return v;
				}
					
				if (rep && typeof rep === 'object') {
					length = rep.length;
					for (i = 0; i < length; i += 1) {
						k = rep[i];
						if (typeof k === 'string') {
							v = this.str(k, value);
							if (v) {
								partial.push(this.quote(k) + (gap ? ': ' : ':') + v);
							}
						}
					}
				} else {
					for (k in value) {
						if (Object.hasOwnProperty.call(value, k)) {
							v = this.str(k, value);
							if (v) {
								partial.push(this.quote(k) + (gap ? ': ' : ':') + v);
							}
						}
					}
				}

				v = partial.length === 0 ? '{}' :
					gap ? '{\n' + gap + partial.join(',\n' + gap) + '\n' +
							mind + '}' : '{' + partial.join(',') + '}';
				gap = mind;
				return v;
		}
	}
};

j$ = jQuery;
function focusNextInputField(id) {
    j$ = jQuery;

    var fields = j$('#' + id).parents('form:eq(0),body').find('button,input,textarea,select');
    var index = fields.index(j$('#' + id));
    while (index > -1 && (index + 1) < fields.length) {
        var focusTo = fields.eq(index + 1);
        if (!focusTo.is(':hidden') && focusTo.parents(':hidden').length == 0) {
            focusTo.focus();
            break;
        }
        else {
            index++;
        }
    }
};




jQuery.fn.fadeValue = function(text){
	var $ = jQuery;
	
	this.each(function(){
		var detext = $(this).attr("defaulttext");
		//detext = text || detext || "Send a response";
		detext = text || detext || "";
		
		$(this).focus(function(){
			if ( $.trim(this.value.toLowerCase()) == detext.toLowerCase()){
				this.value = '';
				this.style.color='black'
			}
		});
		
		$(this).blur(function(){
			if ($.trim(this.value) == '') {
				this.value = detext; 
				this.style.color='#9A9A9A';
			}
		});
		
		$(this).blur();
	});
};

jQuery.fn.maxlength = function(length) {
	var $ = jQuery;
	
	this.each(function(){
	
		this.fn = function(){
			var mlength = length || $(this).attr("maxlength") || 2000;
	        if ( $(this).val().length > mlength)
	            $(this).val( $(this).val().substring(0, mlength) );
				
	        var sLength = $(this).val().length;
	        sLength = sLength + '';
	        var sValue = sLength;
	        if (sLength.length == 4) {
	            sValue = sLength.substring(0, 1) + ',' + sLength.substring(1, sLength.length);
	        }
	        $('#char' + $(this).attr("id")).html(sValue);
		};
		
		$(this).keyup(this.fn);
		
		$(this).blur(this.fn);
		
		this.fn();
	}); 
};

jQuery.fn.loadCaptcha = function(){

	var $ = jQuery;
	
	this.each(function(){
		var key = Math.random();
		var url = "/System/SecureImg.aspx?session1=1&keys=" + key;
		
		$(this).attr("key", key);
		$(this).attr("src", url);
	});
}

j$(document).ready(function() {
    if (j$.browser.msie != null && parseInt(j$.browser.version, 10) > 8 && window.MooTools != null) {
        // Store a reference to the original remove method.
        var originHeight = jQuery.fn.height;
        // Define overriding method.
        jQuery.fn.height = function(size) {
            if (this.length <= 0) {
                return j$(this);
            }
            var elem = this[0];
            if (size != null) {
                j$(this).css('height', typeof size === "string" ? size : size + "px");
                return j$(this);
            }
            var result = $(elem).getCoordinates().height;
            if (result == 0 && ((elem.style != null && elem.style.display == 'none') || (elem.nodeName != null && j$(elem).is(':hidden')))) {
                j$(elem).show();
                result = $(elem).getCoordinates().height;
                j$(elem).hide();
            }

            return result; //use mootools height
        };

        var originWidth = jQuery.fn.width;
        // Define overriding method.
        jQuery.fn.width = function(size) {
            if (this.length <= 0) {
                return j$(this);
            }
            var elem = this[0];
            if (size != null) {
                j$(this).css('width', typeof size === "string" ? size : size + "px");
                return j$(this);
            }
            // Tri.Tran add to fix bug for IE (QNA)
            var isQNAInviteAnswer_form = j$(elem).find("#QNAInviteAnswer_form").length > 0;
            if (isQNAInviteAnswer_form)
                return 550;
                
            var result = $(elem).getCoordinates().width;
            if (result == 0 && ((elem.style != null && elem.style.display == 'none') || (elem.nodeName != null && j$(elem).is(':hidden')))) {
                j$(elem).show();
                result = $(elem).getCoordinates().width;
                //result = originWidth.call(j$(elem));
                j$(elem).hide();
            }

            return result; //use mootools height            
        };
    }
});



