var timezone = "";
$(document).ready(function(){
	timezone = dateFormat("Z");
	if(hasNumbers(timezone)){
		var timeGap = timezone.substring(3)
		if('+0530' == timeGap ){
			timezone = "IST";
		}
	}	
});

function hasNumbers(t){
	return /\d/.test(t);
}

function loadPopup(){
//loads popup only if it is disabled
	//if(popupStatus==0){
	$(".backgroundBlockUIPopup").css({
		"opacity": "0.7"
	});
	$(".backgroundBlockUIPopup").fadeIn("slow");
	$(".popupBlockUI").fadeIn("slow");
	//popupStatus = 1;
	//}
}
//disabling popup with jQuery magic!
function unblockUI(){
//disables popup only if it is enabled
	//if(popupStatus==1){
	$(".backgroundBlockUIPopup").fadeOut("slow");
	$(".popupBlockUI").fadeOut("slow");
	//	popupStatus = 0;
	//}
}
//centering popup
function centerPopup(){
	//request data for centering
	var windowWidth = document.documentElement.clientWidth;
	var windowHeight = document.documentElement.clientHeight;
	var popupHeight = $(".popupBlockUI").height();
	var popupWidth = $(".popupBlockUI").width();
	//centering
	$(".popupBlockUI").css({
		"position": "absolute",
		"top": windowHeight/2,
		"left": windowWidth/2-popupWidth/2
	});
	//only need force for IE6
	$(".backgroundBlockUIPopup").css({
		"height": windowHeight
	});
}

function blockUI(){
	//centering with css
	centerPopup();
	//load popup
	loadPopup();
}
	
function makeDOB(iMonth,iDay,iYear)
{
	var strMonth = "";
	if(iMonth !="" && iDay !="" && iYear !="")
	{
		strMonth = 	getMonthNumberFromName(iMonth)+"/"+iDay+"/"+iYear;
	}
	
	return strMonth;
}

function validateAndSubmit(formName,formUrl){
     blockUI();
      var queryString = getFormString(formName);
	  //var queryString = $("#"+formName).serialize();
      $.ajax
      ({
            url: formUrl,
            type: "POST",
            data:queryString,
            success: function(data){
				if(!data){
					alert("Server Error: Can not process the request. Please try again later.");
	                unblockUI();
					$.modal.close();
					return;
				}
				//parse the JSON to create object
				var obj = eval('(' + data + ')');
                unblockUI();
                if("success" != obj){
                    //this is to clear existing validation error messages
                    $("#"+formName).find("input").map(function(i, e) {
                        $("#"+formName+"_" + e.id + "_err").text("");                        
						$("#"+formName+"_" +  e.id + "_err").css("display","none");
                    });
                    //if there are validation error show them
                    for (var i=0;i<=obj.length;i++) {
						if(obj[i] != null){
	                        $("#"+formName+"_" + obj[i].field + "_err").text(obj[i].message);
							$("#"+formName+"_" + obj[i].field + "_err").css("display","block");
						}
                    }
                    // set the focus on first field
                    // set the focus on first field
					document.getElementById(formName).elements[obj[0].field].focus();
                }else{
                    //clear the form for next time
                    $(':text, :password, :file, SELECT', '#'+formName).val('');  
                    //show the confirmation message
                    document.getElementById(formName+"_form").innerHTML=document.getElementById(formName+"_confirmMsg").innerHTML;
                }
            },
            error: function(xmlHttpRequest, textStatus, errorThrown){
                unblockUI();
            }
      });
}

function validateSubmitAndRedirect(formName,formUrl,redirectURL){
    var queryString = getFormString(formName);
	  //var queryString = $("#"+formName).serialize();
    $.ajax
    ({
          url: formUrl,
          type: "POST",
          data:queryString,
          success: function(data){
				if(!data){
					alert("Server Error: Can not process the request. Please try again later.");
	                unblockUI();
					$.modal.close();
					return;
				}
				//parse the JSON to create object
				var obj = eval('(' + data + ')');
			  
              if("success" == obj) {
            	//clear the form for next time
                  //$(':text, :password, :file, SELECT', '#'+formName).val('');  
                  //show the confirmation message
                  window.location = redirectURL;
              } else if("DUPLICATE" == obj) {
            	  $('#alert_addMedicationDpl').css('display','block');
            	  unblockUI();
              	//alert('Duplication of medication.');
              }else if("OVERLAPPED" == obj) {
            	  $('#alert_addMedicationOvr').css('display','block');
            	  unblockUI();
              	//alert('Duplication of medication.');
              } else {
            	//this is to clear existing validation error messages
                  $("#"+formName).find("input").map(function(i, e) {
                      $("#"+formName+"_" + e.id + "_err").text("");                        
						$("#"+formName+"_" +  e.id + "_err").css("display","none");
                  });
                  $("#"+formName).find("select").map(function(i, e) {
                      $("#"+formName+"_" + e.id + "_err").text("");                        
					  $("#"+formName+"_" +  e.id + "_err").css("display","none");
					  
                  });
                  //if there are validation error show them
                  for (var i=0;i<=obj.length;i++) {
						if(obj[i] != null){
	                        $("#"+formName+"_" + obj[i].field + "_err").text(obj[i].message);
							$("#"+formName+"_" + obj[i].field + "_err").css("display","block");
						}
                  }
                  // set the focus on first field
                  // set the focus on first field
				  document.getElementById(formName).elements[0].focus();
				  unblockUI();
              }
          },
          error: function(xmlHttpRequest, textStatus, errorThrown){
              unblockUI();
          }
    });
}
  function checkBoxSelected(){
	if (!$('#mobileTips').is(':checked')) {
		$('#subscriptionForm_contactNo1').val('');
		$('#subscriptionForm_contactNo2').val('');
		$('#subscriptionForm_contactNo3').val('');
        $('#subscriptionForm_contactNo1').attr('disabled', true);
        $('#subscriptionForm_contactNo2').attr('disabled', true);
        $('#subscriptionForm_contactNo3').attr('disabled', true);
    } else {
        $('#subscriptionForm_contactNo1').removeAttr('disabled');
        $('#subscriptionForm_contactNo2').removeAttr('disabled');
        $('#subscriptionForm_contactNo3').removeAttr('disabled');
    }  
  }
  

  function autoTab(input,len) {
 	 if(input.value.length >= len) {
 	   input.form[(getIndex(input)+1) % input.form.length].focus();
 	 }
 	  return true;
 }

 function getIndex(input) 
 {
 	var index = -1, i = 0, found = false;
 	while (i < input.form.length && index == -1)
 			if (input.form[i] == input)index = i;
 			  else i++;
 			 return index;
 }

function getFormString(elementFormName)
{
	var elementForm = document.getElementById(elementFormName);
	var elLength = elementForm.elements.length;
	var textstring = '';
    for (i=0; i<elLength; i++)
    {
		var element = elementForm.elements[i];
		if(element.disabled){
			continue;
		}
        var type =element.type;
        if (type=="checkbox" && element.checked){
			textstring += (element.name + "=true&");
        }
        else  if (type=="select-one") {
			var user_input = element.options[element.selectedIndex].value
			textstring += (element.name +"="+user_input+"&");
		}
		else  if (type=="hidden") {
			textstring += (element.name+"="+encodeURIComponent(element.value)+"&");
        }
		else  if (type=="text") {
			textstring += (element.name+"="+encodeURIComponent(element.value)+"&");
        }
		else  if (type=="textarea") {
			textstring += (element.name+"="+element.value+"&");
        }
		else{
        }
	}
	return textstring.substring(0,textstring.length-1).replace(/\s+/g,"+") ;
}

function updateMedicationForm(formName,formUrl,medicationId,redirectURL){
   blockUI();
    var queryString = getFormString(formName);
	  //var queryString = $("#"+formName).serialize();
    $.ajax
    ({
          url: formUrl,
          type: "POST",
          data:queryString,
          success: function(data){
				if(!data){
					alert("Server Error: Can not process the request. Please try again later.");
	                unblockUI();
					$.modal.close();
					return;
				}
				//parse the JSON to create object
				var obj = eval('(' + data + ')');
              
              if("success" == obj) {
              	//clear the form for next time
                    //$(':text, :password, :file, SELECT', '#'+formName).val('');  
                    //show the confirmation message
                    window.location = redirectURL;
                } else if("DUPLICATE" == obj) {
                	$('#alert_editMedication'+medicationId+'Dpl').css('display','block');
                	unblockUI();
                	//alert('Duplication of medication.');
                } else if("OVERLAPPED" == obj) {
                	$('#alert_editMedication'+medicationId+'Ovr').css('display','block');
                	unblockUI();
                	//alert('Duplication of medication.');
                } else {
              	//this is to clear existing validation error messages
                    $("#"+formName).find("input").map(function(i, e) {
                        $("#"+formName+"_" + e.id + "_err").text("");                        
  						$("#"+formName+"_" +  e.id + "_err").css("display","none");
                    });
                    $("#"+formName).find("select").map(function(i, e) {
                        $("#"+formName+"_" + e.id + "_err").text("");                        
  					  $("#"+formName+"_" +  e.id + "_err").css("display","none");
  					});
                    //if there are validation error show them
                    for (var i=0;i<=obj.length;i++) {
  						if(obj[i] != null){
  	                        $("#"+formName+"_" + obj[i].field + "_err").text(obj[i].message);
  							$("#"+formName+"_" + obj[i].field + "_err").css("display","block");
  						}
                    }
                    // set the focus on first field
                    // set the focus on first field
  				    //document.getElementById(formName).elements[obj[0].field].focus();
                    document.getElementById(formName).elements[0].focus();
                    unblockUI();
                }
          },
          error: function(xmlHttpRequest, textStatus, errorThrown){
              unblockUI();
          }
    });
}

function deleteMedication(divId,formUrl){
	//alert('Clicked :: ' + divId);
	var queryString = "patientMedicationId="+divId;
	$.ajax({
            url: formUrl,
            type: "POST",
            data:queryString,
            success: function(data){
				if(!data){
					alert("Server Error: Can not process the request. Please try again later.");
	                return;
				}
				//parse the JSON to create object
				$("#medicationNumber"+divId).fadeOut("slow");
            },
            error: function(xmlHttpRequest, textStatus, errorThrown){
                
            }
      });
}


function updateMedicationBlock(medicationId){
	$("#lblMedicationName"+medicationId).text(document.getElementById('medicationName'+medicationId).value);
	$("#lblDosage"+medicationId).text(document.getElementById('dosage'+medicationId).value);
	$("#lblStartDateDesc"+medicationId).text(document.getElementById('startDateDesc'+medicationId).value);
	$("#lblEndDateDesc"+medicationId).text(document.getElementById('endDateDesc'+medicationId).value);
	$("#lblNotes"+medicationId).text(document.getElementById('notes'+medicationId).value);
}

//This is for the date formating
//TODO - Need to see if we can move it out to some other JS file
//---- Start Date Format ---
var dateFormat = function () {
	var	token = /d{1,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|[LloSZ]|"[^"]*"|'[^']*'/g,
		timezone = /\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g,
		timezoneClip = /[^-+\dA-Z]/g,
		pad = function (val, len) {
			val = String(val);
			len = len || 2;
			while (val.length < len) val = "0" + val;
			return val;
		};

	// Regexes and supporting functions are cached through closure
	return function (date, mask, utc) {
		var dF = dateFormat;

		// You can't provide utc if you skip other args (use the "UTC:" mask prefix)
		if (arguments.length == 1 && Object.prototype.toString.call(date) == "[object String]" && !/\d/.test(date)) {
			mask = date;
			date = undefined;
		}

		// Passing date through Date applies Date.parse, if necessary
		date = date ? new Date(date) : new Date;
		if (isNaN(date)) throw SyntaxError("invalid date");

		mask = String(dF.masks[mask] || mask || dF.masks["default"]);

		// Allow setting the utc argument via the mask
		if (mask.slice(0, 4) == "UTC:") {
			mask = mask.slice(4);
			utc = true;
		}

		var	_ = utc ? "getUTC" : "get",
			d = date[_ + "Date"](),
			D = date[_ + "Day"](),
			m = date[_ + "Month"](),
			y = date[_ + "FullYear"](),
			H = date[_ + "Hours"](),
			M = date[_ + "Minutes"](),
			s = date[_ + "Seconds"](),
			L = date[_ + "Milliseconds"](),
			o = utc ? 0 : date.getTimezoneOffset(),
			flags = {
				d:    d,
				dd:   pad(d),
				ddd:  dF.i18n.dayNames[D],
				dddd: dF.i18n.dayNames[D + 7],
				m:    m + 1,
				mm:   pad(m + 1),
				mmm:  dF.i18n.monthNames[m],
				mmmm: dF.i18n.monthNames[m + 12],
				yy:   String(y).slice(2),
				yyyy: y,
				h:    H % 12 || 12,
				hh:   pad(H % 12 || 12),
				H:    H,
				HH:   pad(H),
				M:    M,
				MM:   pad(M),
				s:    s,
				ss:   pad(s),
				l:    pad(L, 3),
				L:    pad(L > 99 ? Math.round(L / 10) : L),
				t:    H < 12 ? "a"  : "p",
				tt:   H < 12 ? "am" : "pm",
				T:    H < 12 ? "A"  : "P",
				TT:   H < 12 ? "AM" : "PM",
				Z:    utc ? "UTC" : (String(date).match(timezone) || [""]).pop().replace(timezoneClip, ""),
				o:    (o > 0 ? "-" : "+") + pad(Math.floor(Math.abs(o) / 60) * 100 + Math.abs(o) % 60, 4),
				S:    ["th", "st", "nd", "rd"][d % 10 > 3 ? 0 : (d % 100 - d % 10 != 10) * d % 10]
			};

		return mask.replace(token, function ($0) {
			return $0 in flags ? flags[$0] : $0.slice(1, $0.length - 1);
		});
	};
}();

// Some common format strings
dateFormat.masks = {
	"default":      "ddd mmm dd yyyy HH:MM:ss",
	shortDate:      "m/d/yy",
	mediumDate:     "mmm d, yyyy",
	longDate:       "mmmm d, yyyy",
	fullDate:       "dddd, mmmm d, yyyy",
	shortTime:      "h:MM TT",
	mediumTime:     "h:MM:ss TT",
	longTime:       "h:MM:ss TT Z",
	isoDate:        "yyyy-mm-dd",
	isoTime:        "HH:MM:ss",
	isoDateTime:    "yyyy-mm-dd'T'HH:MM:ss",
	isoUtcDateTime: "UTC:yyyy-mm-dd'T'HH:MM:ss'Z'"
};

// Internationalization strings
dateFormat.i18n = {
	dayNames: [
		"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat",
		"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"
	],
	monthNames: [
		"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
		"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"
	]
};

// For convenience...
Date.prototype.format = function (mask, utc) {
	return dateFormat(this, mask, utc);
};
//---- End Date Format ---

// functions for calendar component.
function numberOfDays(year, month) {
    return new Date(year, month, 0).getDate();
}
var arrMonths = ['January','February','March','April','May','June','July','August','September','October','November','December'];
/***common function which provides calendar functionality for drop downs**/
function populateCalendar(divId){
	var dayList,monthList,yearList,currentDate = new Date(),tempDate = new Date();
	monthList = $('#'+divId).find('select')[0];
	dayList = $('#'+divId).find('select')[1];
	yearList = $('#'+divId).find('select')[2];
	var selectedDay = dayList.value,year = yearList.value,month=monthList.selectedIndex,selectedMonth=monthList.value;
	if(year != ''){
		currentDate = new Date(year, month-1, 0);
	} else {
		year = currentDate.getFullYear() -1;
	}
	for(i=dayList.options.length-1;i>=0;i--) {
		dayList.remove(i);
	}
	for(i=monthList.options.length-1;i>=0;i--) {
		monthList.remove(i);
	}
	var option = document.createElement("option");
	option.text = 'Day';
	option.value = '';
	try {
		dayList.add(option, null); //Standard
	}catch(error) {
		dayList.add(option); // IE only
	}
	if(year == tempDate.getFullYear()) {
		// year is current year restrict user from selecting future date
		
		var option1 = document.createElement("option");
			option1.text = 'Month';
			option1.value = '';
		try {
			monthList.add(option1, null); //Standard
		}catch(error) {
			monthList.add(option1); // IE only
		}
		for(var i=0;i<=tempDate.getMonth();i++){
			option = document.createElement("option");
		    option.text = arrMonths[i];
		    option.value = arrMonths[i];
		    try {
		        monthList.add(option, null); //Standard
		    }catch(error) {
		        monthList.add(option); // IE only
		    }
		}
		if(tempDate.getMonth() == month-1) {
			for(var i=1;i<=tempDate.getDate();i++){
				option = document.createElement("option");
				option.text = i;
				option.value = i;
			    try {
			        dayList.add(option, null); //Standard
			    }catch(error) {
			        dayList.add(option); // IE only
			    }
			}
		} else {
			for(var i=1;i<=numberOfDays(year,month);i++){
				option = document.createElement("option");
				option.text = i;
				option.value = i;
			    try {
			        dayList.add(option, null); //Standard
			    }catch(error) {
			        dayList.add(option); // IE only
			    }
			}
		}
	} else {
		// user has selected past year
		var option = document.createElement("option");
		option.text = 'Month';
		option.value = '';
		try {
			monthList.add(option, null); //Standard
		}catch(error) {
			monthList.add(option); // IE only
		}
		for(var i=0;i<arrMonths.length;i++) {
			option = document.createElement("option");
		    option.text = arrMonths[i];
		    option.value = arrMonths[i];
		    try {
		        monthList.add(option, null); //Standard
		    }catch(error) {
		        monthList.add(option); // IE only
		    }
		}
		for(var i=1;i<=numberOfDays(year,month);i++){
			option = document.createElement("option");
		    option.text = i;
		    option.value = i;
		    try {
		        dayList.add(option, null); //Standard
		    }catch(error) {
		        dayList.add(option); // IE only
			}
		}
	}
	var dayValueFound = false;
	for(i=0;i<=dayList.options.length-1;i++) {
		if(dayList.options[i].value == selectedDay){
			dayValueFound = true;
			break;
		}
	}
	
	var monthValueFound = false;
	for(i=0;i<=monthList.options.length-1;i++) {
		if(monthList.options[i].value == selectedMonth){
			monthValueFound = true;
			break;
		}
	}
	
	if(dayValueFound){
		dayList.value = selectedDay;
	} else {
		dayList.value = '';
	}
	
	if(monthValueFound){
		monthList.value = selectedMonth;
	} else {
		monthList.value = '';
	}
}

function calculateTime(lstId,mon,dy,yr) {
	var forPeriod='',periodVal;
	forPeriod = $('input:radio[name=periodDesc]:checked').val()+'';
	periodVal = $('#'+lstId).val();
	if(periodVal !='' && forPeriod !='undefined'){
		var currentDate = new Date();
		if(forPeriod =='Days') {
			currentDate.setDate(currentDate.getDate()-periodVal);
		} else if(forPeriod =='Weeks') {
			currentDate.setDate(currentDate.getDate()-periodVal*7);
		} else if(forPeriod =='Months') {
			currentDate.setMonth(currentDate.getMonth()-periodVal);
		} else if(forPeriod =='Years') {
			currentDate.setYear(currentDate.getFullYear()-periodVal);
		}
		var year = currentDate.getFullYear();
		var x=document.getElementById(mon).selectedIndex;
		var y=document.getElementById(mon).options;
		$('#'+mon).val(y[currentDate.getMonth()+1].text);
		$('#'+yr).val(year);
		var daysInAMonth = numberOfDays(year,currentDate.getMonth()+1);
		$('#'+dy+' option').each(function(i, option){ $(option).remove();});
		$('#'+dy).append('<option value="">Select</option>');
		for(var i=1;i<=daysInAMonth;i++){
			$('#'+dy).append('<option value=\"'+i+'\">'+i+'</option>');
		}
		$('#'+dy).val(currentDate.getDate());
	}
}


function getMonthNumberFromName(strMonth)
{
	var iMonth = "00";
	if(strMonth == 'January'){
		iMonth ="01";
	}
	else if(strMonth == 'February'){
		iMonth ="02";
	}
	else if(strMonth == 'March'){
		iMonth ="03";
	}	
	else if(strMonth == 'April'){
		iMonth ="04";
	}
	else if(strMonth == 'May'){
		iMonth ="05";
	}
	else if(strMonth == 'June'){
		iMonth ="06";
	}
	else if(strMonth == 'July'){
		iMonth ="07";
	}
	else if(strMonth == 'August'){
		iMonth ="08";
	}
	else if(strMonth == 'September'){
		iMonth ="09";
	}
	else if(strMonth == 'October'){
		iMonth ="10";
	}
	else if(strMonth == 'November'){
		iMonth ="11";
	}
	else if(strMonth == 'December'){
		iMonth ="12";
	}
	return iMonth;
}


function getMonthIndexByName(strMonth)
{
	var iMonth = "";
	if(strMonth == 'January'){
		iMonth ="01";
	}
	else if(strMonth == 'February'){
		iMonth ="02";
	}
	else if(strMonth == 'March'){
		iMonth ="03";
	}	
	else if(strMonth == 'April'){
		iMonth ="04";
	}
	else if(strMonth == 'May'){
		iMonth ="05";
	}
	else if(strMonth == 'June'){
		iMonth ="06";
	}
	else if(strMonth == 'July'){
		iMonth ="07";
	}
	else if(strMonth == 'August'){
		iMonth ="08";
	}
	else if(strMonth == 'September'){
		iMonth ="09";
	}
	else if(strMonth == 'October'){
		iMonth ="10";
	}
	else if(strMonth == 'November'){
		iMonth ="11";
	}
	else if(strMonth == 'December'){
		iMonth ="12";
	}
	return iMonth;
}

