var panelCtr = 0;
function cmsPanel( opt )
{
    this.init( opt );   
}

cmsPanel.prototype = {
    init:function( opt )
    {
        this.ctr = panelCtr++;
        var pWidth = (opt.width != null && opt.width!='' )?opt.width:300;
        var pHeight = ( opt.height!= null )?opt.height:'auto'; 
    	  var pTitle = (opt.title != null && opt.title!='' )?opt.title:'Loading, Please wait...';
    	  var pMsg  = (opt.msg != null && opt.msg!='' )?opt.msg:'<div align="center"><img src="cms/scripts/jquery/loading.gif"></div>';
        if( $('#resultPanel' + this.ctr).length == 0)
        {
        	  $(document.body).append('<div title="'+pTitle+'" id="resultPanel'+this.ctr+'">'+pMsg+'</div>');
        	  $('#resultPanel'+this.ctr).dialog({
        	  	modal:true,
        	  	width:pWidth,
        	  	draggable:false,
        	  	minHeight:10,
        	  	resizable:false,
        	  	autoOpen:false,
        	  	height:pHeight
        	  });
        	   var dialogParent = $('#resultPanel').parent();
        	  $('.ui-dialog-titlebar-close', dialogParent).css('display', 'none');
        }
        else
        {
        	  $('#resultPanel' +this.ctr).html(pMsg);
        		$('#ui-dialog-title-resultPanel'+this.ctr).html(pTitle);
        		$('#resultPanel'+this.ctr).dialog('open');
        		
        }
    },
    
    setTitle:function(pTitle )
    {
        $('#ui-dialog-title-resultPanel'+this.ctr).html(pTitle);
    },
    
     setContent:function(pContent )
    {
        $('#resultPanel'+this.ctr).html(pContent);
    },
    
    show:function()
    {
        $('#resultPanel'+this.ctr).dialog('open');  
    },
    
    hide:function()
    {
        $('#resultPanel'+this.ctr).dialog('close');   
    },
    
    setWaitingContent:function()
    {
        var pTitle = 'Loading, Please wait...';
    	  var pMsg  = '<div align="center"><img src="nrc/scripts/jquery/loading.gif"></div>';
    	  this.setContent( pMsg );
    	  this.setTitle( pTitle );
    }
}

var numberOnly = function( ev ) {
	try
	{
		var charcode = ( ev.charCode != null)?ev.charCode:ev.keyCode;
		
	  var character = String.fromCharCode(charcode);
	 
	  if ((charcode==null) || (charcode==0) || (charcode==8) || 
	      (charcode==9) || (charcode==13) || (charcode==27) )
	    return true;
	  if (("1234567890").indexOf(character) > -1)
	    return true;
	}
	catch(E)
	{
			return true;
	}
  return false;
}

var decimalOnly = function( ev ) {
	
	try
	{
		var charcode = ( ev.charCode != null)?ev.charCode:ev.keyCode;
		
	  var character = String.fromCharCode(charcode);
	 
	  if ((charcode==null) || (charcode==0) || (charcode==8) || 
      (charcode==9) || (charcode==13) || (charcode==27) )
    	return true;
  	if (("-1234567890.").indexOf(character) > -1)
    	return true;
	}
	catch(E)
	{
		return true;
	}
  return false;
	
}

var alphaNumericOnly = function( ev ) {
	try
	{
		var charcode = ( ev.charCode != null)?ev.charCode:ev.keyCode;
		
	  var character = String.fromCharCode(charcode);

	  if ((charcode==null) || (charcode==0) || (charcode==8) || 
	      (charcode==9) || (charcode==13) || (charcode==27) )
	    return true;
	  if (("0123456789.abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_").indexOf(character) > -1)
	    return true;
	}
	catch(E)
	{
		return true;
	}
  return false;
}

var customCharSet = function( ev, characterSet ) {
	try
	{
		var charcode = ( ev.charCode != null)?ev.charCode:ev.keyCode;
		
	  var character = String.fromCharCode(charcode);
	 
	  
	 	// control keys
	  if ((charcode==null) || (charcode==0) || (charcode==8) || 
	      (charcode==9) || (charcode==13) || (charcode==27) )
	    return true;
	  else if (characterSet.indexOf(character) > -1)
	    return true;
	}
	catch(E)
	{
		return true;
	}
  return false;
}

var isEmail = function(str) {

		var at="@"
		var dot="."

		var lat=str.indexOf(at)
		var lstr=str.length
		var ldot=str.indexOf(dot)
		if (str.indexOf(at)==-1){
		   return false
		}

		if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
		   return false
		}

		if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
		    return false
		}

		 if (str.indexOf(at,(lat+1))!=-1){
		    return false
		 }

		 if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
		    return false
		 }

		 if (str.indexOf(dot,(lat+2))==-1){
		    return false
		 }
		
		 if (str.indexOf(" ")!=-1){
		    return false
		 }

 		 return true					
}

var dump = function(ob, print_method ){
			var str = '';
			
			if( ob instanceof Array )
			{
					for( i=0; i<ob.length; i++ ) {
						str += i + ':' + ob[i] + '\n';
					}
			}
			else
		  {
				for( item in ob ) {
					str += item + ':' + ob[item] + '\n';
				}
			}
			if( print_method == 'write') {
				var newwin = window.open('about:blank');
				newwin.document.write(str);
			}
			else {
				alert(str);
			}
}

var in_array = function( val, arr ){
	if( !arr instanceof Array ) {
		return false;
	}
	
	for( var i=0; i<arr.length; i++ ){
		if( val == arr[i] ) {
			return true;
		}
	}
	
	return false;
}

var dateDiff = function(unit, from, to) {
	var one_unit = 1;
	if( unit == 'day' ) {
		one_unit=1000*60*60*24;
	}
	//Calculate difference btw the two dates, and convert to days
	return Math.ceil((to.getTime()-from.getTime())/(one_unit));
}

var clone = function (obj) {

        if(obj == null || typeof(obj) != 'object') return obj;



        if(obj.constructor == Array) {

                var temp = [];

                for(var i = 0; i < obj.length; i++) {

                        if(typeof(obj[i]) == 'object')   temp.push(clone(obj[i]));

                        else temp.push(obj[i]);

                }

                return temp;

        }



        var temp = {};

        for(var key in obj) temp[key] = clone(obj[key]);

        return temp;

}

function isnumeric(strString)
   //  check for valid numeric strings	
   {
   var strValidChars = "0123456789.";
   var strChar;
   var blnResult = true;

   if (strString.length == 0) return false;

   //  test strString consists of valid characters listed above
   for (i = 0; i < strString.length && blnResult == true; i++)
      {
      strChar = strString.charAt(i);
      if (strValidChars.indexOf(strChar) == -1)
         { 
         blnResult = false;
         }
	  
      }
   return blnResult;
   }

function formatDecimal(field, decimalPlace )
{	
	 if(decimalPlace == null || decimalPlace=='')
	 {
	 		decimalPlace = 2;
	 }
	 
   if(field.value!='')
   {
      if(!isnumeric(field.value))
      {    alert("please enter this field with numeric value in xxxx.xx format.");
           field.value ='';       
      }
      else if(parseFloat(field.value)==0)
      {
          alert("The value of this field cannot be zero.");
          field.value ='';
      }
      else
      {		
          var amt = parseFloat(field.value);
          var temp = amt.toFixed(decimalPlace);
          if( temp.indexOf('.') == -1 ) {
          	temp += '.';
          	for( var i=0; i<decimalPlace; i++ )
          	{
          			temp+='0';
          	}	
          }
          field.value = temp;
      }
      
   }
}

function getRadioValue( field )
{
		if( field.length )
		{
	    for( var i=0; i<field.length; i++)
	    {
	        if( field[i].checked )
	        {
	            return field[i].value;   
	        }   
	    }
	  }
	  else
	 	{
	 		 if( field.checked )
	 		 {
	 		 		return field.value;
	 		 }
	 		 else
	 		 {
	 		 		return '';
	 		 }
	 	}
}


function tickAllCheckBox(val, fm )
{		
		if( val == true )
				$('input[type=checkbox]', fm).attr({'checked':'checked'});
		else
				$('input[type=checkbox]', fm).removeAttr('checked');
		
}
function isDate(dateStr) {

	var datePat = /^(\d{1,2})(\/|-)(\d{1,2})(\/|-)(\d{4})$/;
	var matchArray = dateStr.match(datePat); // is the format ok?
	
	
	if (matchArray == null) {
		return false;
	}

	month =parseFloat(matchArray[3]); // p@rse date into variables
	day = parseFloat(matchArray[1]);
	year = parseFloat(matchArray[5]);
	
	
	if (month < 1 || month > 12) { // check month range
		return false;
	}

	if (day < 1 || day > 31) {
		return false;
	}

	if ((month==4 || month==6 || month==9 || month==11) && day==31) {
		return false;
	}
	
	if (month == 2) { // check for february 29th
	   var isleap = (year % 4 == 0);
	   if (day>29||(day==29&&!isleap)) {
		return false;
	  }
    }
return true; // date is valid
}

var panel;
$(document).bind('ready', function() {
		if( panel == null )
			panel = new cmsPanel({'width':'350px'});
});

var sp = "\n";
var cntValidate = function(sp)
{
		this.sp = sp;
}

cntValidate.prototype = {
	"required": function( fieldname, label, fieldtype, overridemsg )
	{
			if ( jQuery.trim($('#' + fieldname).val()) == '')
			{
					if( overridemsg != null && overridemsg != '' )
						return overridemsg+this.sp;
					else
						return 'Please key in ' + label +'.' +this.sp;		
			}
			
			return '';
	},
	"email": function( fieldname, label, overridemsg )
	{	
			var val = jQuery.trim($('#'+fieldname).val() );
			if( val !='' && !isEmail(val) )
			{		
					return (  overridemsg != null && overridemsg != ''  )?overridemsg +this.sp: 'Please verify ' + label +'\'s format.' +this.sp;		
			}
			return '';
	},
	"password":function( fieldname, label, minlength )
	{
			var val = $('#'+fieldname).val();
			if( val != '' && val.length < minlength )
			{
					return label +' must be at least ' +minlength + ' characters.' + this.sp;
			}
			return '';
	},
	"confirmpassword":function( fieldname, repeat_fieldname, label )
	{
			var val = $('#'+fieldname).val();
			var repeatval = $('#'+repeat_fieldname).val();
			if( val != '' && val != repeatval )
			{
					return label +' must be same with Password.' + this.sp;
			}
			return '';
	},
	
	"date": function( fieldname, label, overridemsg )
	{
			var val = $('#'+fieldname).val();
			if( val!= '' && !isDate( val, 'dd/MM/yyyy') )
			{
					return (  overridemsg != null && overridemsg != ''  )?overridemsg +this.sp:'Please verify ' + label + "'s format. Correct format is dd/mm/yyyy." + this.sp
			}	
			
			return '';
	}
}


