String.prototype.replaceAll  = function(s1,s2){
	return this.replace(new RegExp(s1,"gm"),s2);
}

function menu( options ){
	
	var fromElement = $( options.fromElement ),
	contentElement =  $( options.contentElement );
	var fromOffset = fromElement.offset(),
	safari = /safari/.test(window.navigator.userAgent.toLowerCase()) ? 20 : 0;
	contentElement.css({position:'absolute',display:'block',zIndex:2,top:fromOffset.top + fromElement.outerHeight()-safari,left:fromOffset.left});
	var x1 = fromOffset.left,
	x2 = fromOffset.left + contentElement.outerWidth(),
	y1 = fromOffset.top - safari,
	y2 = fromOffset.top - safari + contentElement.outerHeight();
	$( document ).mousemove(function(e){
		if( e.pageX < x1 || e.pageX > x2 || e.pageY < y1 || e.pageY > y2 ){
			contentElement.hide();
			$(this).unbind('mousemove',arguments.callee);
		}
	});
}

function removeLinebreak (s) {
	var ss = s;
    ss = ss.replace(/(\n(\s*\n)+)/g,"\n");
    ss = ss.replace(/\r\n$/,"");
    return ss;
}

function isEmailFormatValid(fieldVal) {
	var regexp = new RegExp("^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$");
	return fieldVal.match(regexp);
}

function htmlDecode(str) {
	str = str.replaceAll("&lt;","<");
	str = str.replaceAll("&gt;",">");
	str = str.replaceAll("&amp;","&");

	return str;
}


function text2Unicode(str) {
  var result = "";

  for(i = 0 ; i < str.length ; i++) {
    c = str.charAt(i);
    if((' ' <= c && c <= '~') || (c == '\r') || (c == '\n')) {
      if(c == '&') {
        cstr = "&amp;";
      } else if(c == '<') {
        cstr = "&lt;";
      } else if(c == '>') {
        cstr = "&gt;";
      } else {
        cstr = c.toString();
      }
    } else {
      cstr = "&#" + c.charCodeAt().toString() + ";";
    }
      result = result + cstr;
  }

  return result;
}

function removeHTMLTag(inputStr) {
	var re = new RegExp("\<[^\>]+\>","g");
	return inputStr.replace(re,"");
}

$(document).ready(function(){
	$.extend($.fn, {
		selectRange: function(start, end) {
		    if ($(this).get(0).createTextRange) {
		        var range = $(this).get(0).createTextRange();
		        range.collapse(true);
		        range.moveEnd('character',   end);
		        range.moveStart('character', start);
		        range.select();
		    }
		    else if ($(this).get(0).setSelectionRange) {
		        $(this).focus().get(0).setSelectionRange(start, end);
		    }
		    return $(this);
		}
	});
});

function showCover() {
  if ($("screenCover").length == 0) {
    $("body").append('<span id="screenCover" class="hide"></span>')
   }

	if ($("#screenCover")) {
		var h = $(document).height()+"px";
		var w = $(document).width()+"px";

		$("#screenCover").css({
			backgroundColor: "#000000",
			position: "absolute",
			left: "0px",
			top: "0px",
			height: h,
			width: w,
			zIndex: "1000"
		}).fadeTo(1, 0.5).show();
	}
}

function hideCover() {
	if ($("#screenCover")) {
		$("#screenCover").hide();
	}
}

/**
 * Generate a random number
 */
function keyGen() {
	rnd.today=new Date();
	rnd.seed=rnd.today.getTime();

	return rand(10000000)-1;

	function rnd() {
	        rnd.seed = (rnd.seed*9301+49297) % 233280;
	        return rnd.seed/(233280.0);
	};

	function rand(number) {
	        return Math.ceil(rnd()*number);
	};
}

function unsetMailCookie() {
	$.cookie('mailCookie', null);
}

function setMailCookie(profileId, content) {
	content = profileId+"|"+content;
	$.cookie('mailCookie', content);
}

function getMailCookie(profileId) {
	var mailCookie = $.cookie('mailCookie');
	if (mailCookie != null) {
		var cookieProfileId = mailCookie.split("|")[0];
		var cookieContent =  mailCookie.split("|")[1];

		if (cookieProfileId!=profileId) {
			unsetMailCookie();
			return "";
		} else {
			return cookieContent;
		}
	}

	return "";
}

	function loadRegions(countryId, regionBlockId) {
		var regionsId = regionBlockId;
		if (countryId.constructor==Array && countryId.length>1) {
			$("#"+regionsId).html("");
		} else {
			$.post("/js/regions.jhtml", {countryCode: countryId},
				function(data){
					var opt = '';
					$(data).find("region").each(function() {
						var regionText = $(this).text();
						var regionId =  $(this).attr("id");
						opt += "<option value='"+regionId+"'>"+regionText+"</option>";
					});
					$("#"+regionsId).html(opt);
			  	}, "xml");
		}
	}

		function showErr(tabId, showAllErr) {
			var selectorStr = tabId==null ? "span[id^='err_']" : "#"+tabId+" span[id^='err_']";
			showAllErr = showAllErr==null ? true : showAllErr;

			var errCount = 0;
			var firstErrId = '';
			$(selectorStr).each(function() {
				if ($.trim($(this).text()).length > 0) {
					var id = $(this).attr("id");
					if (showAllErr || errCount==0) {
						if (firstErrId=='') {
							firstErrId = id.replace("err_","");
						}
						$(this).css("display","block");
						errCount++;
					}
				}
			});

			return firstErrId;
		}

		function setFocus(fieldId) {
			$("#"+fieldId).focus();
			try {
				$("#"+fieldId).select();
			} catch (e) {}
		}

		function isFieldEmpty(checkId) {
			var result = true;

			$('#'+checkId).each(
				function() {
					var type = this.type;
					if (type == 'text' || type == 'password') {
						result = $.trim(this.value).length <= 0;
					} else if (type == 'select-one') {
						result = this.value=='';
					} else if (type=='select-multiple') {
						if ( $("select[id=matchEthnicities] option:selected").length == 1) {
							result = this.value=='';
						} else {
							result = $("select[id="+checkId+"] option:selected").length == 0;
						}
					} else if (type == 'checkbox') {
						result = $("input[id="+checkId+"]:checked").length == 0;
					} else if (type == 'radio') {
						result = $(":radio[id="+checkId+"]:checked").val() ? false : true;
					} else if (type == 'textarea') {
						result = $.trim($(this).val()).length <= 0;
					}
				}
			);

			return result;
		}

		function confirmBoxHTML(boxid, confirmAction) {
			var html = "";
			html+='	<span id="'+boxid+'" style="display:none">';
			html+='	    <table width="100%" border="1" cellspacing="0" cellpadding="8" class="bg_green_wrap">';
			html+='	   	<tr>';
			html+='	        <td>';
			html+='	        	<div class="bg_white_box">';
			html+='		            <table width="100%" border="0" align="center" cellpadding="8" cellspacing="0" class="margin_space">';
			html+='		         	<tr>';
			html+='		            	<td align="center">';
			html+='		            		<h3 class="fontcolor_red" id="confirmMessage"></h3>';
			html+='		            		<br><br>';
			html+='		            		<input type="button" class="input_btn_style1" id="confirmMessageButton" onclick="'+boxid+'_'+confirmAction+'"/>';
			html+='		            	</td>';
			html+='		          	</tr>';
			html+='		            </table>';
			html+='	        	</div>';
			html+='			</td>';
			html+='	   	</tr>';
			html+='	    </table>';
			html+='	</span>';
			return html;

		}

jQuery.fn.maxlength = function(){
    $("textarea[maxlength]").keypress(function(event){
        var key = event.which;
        //all keys including return.
        if(key >= 33 || key == 13) {
            var maxLength = $(this).attr("maxlength");
            var length = this.value.length;

            if(length >= maxLength) {
                event.preventDefault();
            }
        }
    });
}

$(document).ready(function(){
	$().maxlength();
});