var one_day=1000*60*60*24;
function GetData(rlnr,rltb,token,lang,readonly){
   if (rlnr==0) {return;}
   $.ajax({
      type: "GET",
      url: "jx_getdbdata.php?lang="+lang+"&idc="+rlnr+"&idt="+rltb+"&token="+$('#token').val(),
      dataType: "json",
      cache: false,
      contentType: "application/json",
      success: function(data) {
         for (key in  data ){  
            if (data[key]['fieldtype']=='check'){ if (data[key]['data']==0){ $('#'+data[key]['fieldname']).attr({'checked':false}); } else { $('#'+data[key]['fieldname']).attr({'checked':true}); }
            } else if (data[key]['fieldtype']=='option'){ if (data[key]['data']==1){ $('#'+data[key]['fieldname']+'_yes').attr('checked', true); } else { $('#'+data[key]['fieldname']+'_no').attr('checked', true); }
            } else if (data[key]['fieldtype']=='text'){ $('#'+data[key]['fieldname']).val(data[key]['data']); 
            } else if (data[key]['fieldtype']=='html'){ $('#'+data[key]['fieldname']).html(data[key]['data']); 
            }
        }
      },
      error: function(xhr, status, error) {
         alert(xhr.status);
      }
   });
}
function EmailFormat(eField,msgWrong){
    if ($('#'+eField).val().length==0) {return true; } var emailExp = /^[\w\-\.\+]+\@[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,4}$/; if($('#'+eField).val().match(emailExp)){ $('#'+eField).css({'borderColor':''}); return true; } else { alert(msgWrong); $('#'+eField).css({'borderColor':'red'}); return false;} 
}
function noCaps(eField) {  
   $('#nocaps').hide(2);$('#spacer').show(2); var regexp = /[A-Z]/g;
   if (eField=='postalcode' || eField=='emailaddress') return; 
   var text = $('#'+eField).val(); if (text.length==0) return;
   var lowText=text.toLowerCase(); var matchList = text.match(regexp); 
   var percentage=(matchList!=null) ? matchList.length/text.length * 100:0;
   if ( percentage >= 30 || text==lowText) {
      $('#nocaps').show(2); $('#spacer').hide(2); var strSep = (eField=='remark' || eField=='text') ?'. ':' '; var strWords=text.toLowerCase().split(strSep); for (i=0;i<strWords.length;i++){ var firstLetter = strWords[i].substr(0, 1); strWords[i]=firstLetter.toUpperCase() + strWords[i].substr(1); } $('#'+eField).val(strWords.join(strSep));
   }  
}  
function CalcRates(exc){
  if (!exc) { 
    if($('#curr_MYR').val()=='-') return;
    AmountFormat('curr_MYR',2); var myr=$('#curr_MYR').val(); if (myr<=0){ alert($('#TRANS10848').val()); } var nAmount; var ArCurrs=$('#exrates').val().split('|'); for ($i=0;$i<ArCurrs.length;$i++){ nAmount=myr*$('#base_'+ArCurrs[$i]).val(); var DecPlaces=(ArCurrs[$i]=='MYR')? 2:2; $('#curr_'+ArCurrs[$i]).val(nAmount.toFixed(DecPlaces)); }
  } else {
    if($('#curr_'+exc).val()=='-') return;
    AmountFormat('curr_'+exc,2); var myr=$('#curr_'+exc).val(); if (myr<=0){ alert($('#TRANS10848').val());	} var nAmount; var ArCurrs=$('#exrates').val().split('|'); for ($i=0;$i<ArCurrs.length;$i++){ if (ArCurrs[$i]!=exc){ nAmount=myr*($('#base_'+ArCurrs[$i]).val()/$('#base_'+exc).val()); $('#curr_'+ArCurrs[$i]).val(nAmount.toFixed(2));}}
  }
}

function CalculateDays(){
    var ChkDate=$('#arrival').val().split('/');
    var StartDate=new Date(ChkDate[2],ChkDate[1]-1,ChkDate[0]);
    var TestAdate=ChkDate[2]+'-'+ChkDate[1]+'-'+ChkDate[0];
    var ChkDate=$('#departure').val().split('/');
    var EndDate=new Date(ChkDate[2],ChkDate[1]-1,ChkDate[0]);
    var TestDdate=ChkDate[2]+'-'+ChkDate[1]+'-'+ChkDate[0];
    var one_day=1000*60*60*24;
    var Totdays=Math.ceil((EndDate.getTime()-StartDate.getTime())/(one_day));
    $('#nightstostay').val(Totdays);   
}
function DisplayMessage(msg){
    $('#alert').html(msg);
    $( '#dialog-message' ).dialog({ 
      modal: true,
	   buttons: {
				Ok: function() {
					$( this ).dialog( 'close' );
				}
			}
		});
}
function AmountFormat(AmountField,DecPlaces){
     var newPrice=""; var valPrices=$('#'+AmountField).val(); var lenPrices=valPrices.length; if (lenPrices==0){return}; var strTemp =""; var chrAllowed="0123456789.,-"; var dotcount=0; var negnumber=0;
     for (i=lenPrices;i>=0;i--){ 
         if(chrAllowed.indexOf(valPrices.charAt(i)) != -1) { 
             if (valPrices.charAt(i)!='.' && valPrices.charAt(i)!=',') { newPrice = valPrices.charAt(i) + newPrice; if (valPrices.charAt(i)=='-'){ break; } } else { strTemp='.'; if (dotcount==0 && newPrice!==""){ newPrice=strTemp + newPrice; dotcount=1;} } 
         } 
     }
     newPrice = parseFloat(newPrice).toFixed(DecPlaces); if (newPrice==='NaN') { newPrice="0"; } newPrice = parseFloat(newPrice).toFixed(DecPlaces); if (newPrice!=valPrices){ $('#'+AmountField).val(newPrice); return; } 
}
function SetCookie(cookieName,cookieValue,nDays) {
    // all cookies are deleted at closing browser/session
    var today = new Date();
    var expire = new Date();
    if (nDays==null || nDays==0) nDays=1;
    expire.setTime(today.getTime() + 3600000*2*nDays);
    document.cookie = cookieName+'='+escape(cookieValue);
}	 
function GetCookie(check_name) {
	// first we'll split this cookie up into name/value pairs
	// note: document.cookie only returns name=value, not the other components
	var a_all_cookies = document.cookie.split( ';' );
	var a_temp_cookie = '';
	var cookie_name = '';
	var cookie_value = '';
	var b_cookie_found = false; // set boolean t/f default f
	for ( i = 0; i < a_all_cookies.length; i++ ){
		// now we'll split apart each name=value pair
		a_temp_cookie = a_all_cookies[i].split( '=' );
		// and trim left/right whitespace while we're at it
		cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');
		// if the extracted name matches passed check_name
		if ( cookie_name == check_name ) {
			b_cookie_found = true;
			//we need to handle case where cookie has no value but exists (no = sign, that is):
			if ( a_temp_cookie.length > 1 )	{
				cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') );
			}
			// note that in cases where cookie is initialized but no value, null is returned
			return cookie_value;
			break;
		}
		a_temp_cookie = null;
		cookie_name = '';
	}
	if ( !b_cookie_found ){
		return null;
	}
}				
function checkTimeZone() {
    // current date and time of user
    var rightNow = new Date();
    var date5 = rightNow;
    // first januari 1st for this user
    var date1 = new Date(rightNow.getFullYear(), 0, 1, 0, 0, 0, 0);
    // find july 1st for this user
    var date2 = new Date(rightNow.getFullYear(), 6, 1, 0, 0, 0, 0);
    // convert januari 1st to GMT
    var temp = date1.toGMTString();
    var date3 = new Date(temp.substring(0, temp.lastIndexOf(" ")-1));
    // convert july 1st to GMT 
    var temp = date2.toGMTString();
    var date4 = new Date(temp.substring(0, temp.lastIndexOf(" ")-1));
    // convert current time to GMT    
    var temp = date5.toGMTString();
    var date6 = new Date(temp.substring(0, temp.lastIndexOf(" ")-1));
    // find the difference in hours between januari 1 user and januari 1 GMT
    var hoursDiffStdTime = (date1 - date3) / (1000 * 60 * 60);
    $('#timezone').val(hoursDiffStdTime);
}
