function acceptChar(objtextbox)
{
    var exp = /[^\A-Za-z\.-]/g;
    objtextbox.value = objtextbox.value.replace(exp,'');
}
function acceptPhone(objtextbox)
{
    var exp = /[^\d\-]/g;
    objtextbox.value = objtextbox.value.replace(exp,'');
}
function acceptDigits(objtextbox)
{
    var exp = /[^\d]/g;
    objtextbox.value = objtextbox.value.replace(exp,'');
}
function AcceptDigits1(objtextbox)
{
    var exp = /[^\d.]/gi;
    objtextbox.value = objtextbox.value.replace(exp,'');
}
function acceptDecimal(objtextbox)
{
    var exp = /[^\d.]/g;
    objtextbox.value = objtextbox.value.replace(exp,'');
}

function checkEmail(email)
{
    if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(email))
    {
        return true;
    }
    return false;
}

function check_url(ctrl)
{
    var theurl = ctrl.value;
    var tomatch = /http:\/\/[A-Za-z0-9\.-]{3,}\.[A-Za-z]{3}/

    if(tomatch.test(theurl))
        return true;
    else
        return false;
}

function isValidURL(url)
{
    var RegExp = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/;

    if(RegExp.test(url)){
        return true;
    }else{
        return false;
    }
}

function GetCursorLocation(CurrentTextBox)
{
	var CurrentSelection, FullRange, LocationIndex = -1;
	if (typeof CurrentTextBox.selectionStart == "number")
	{
		LocationIndex = CurrentTextBox.selectionStart;
	}
	else if (document.selection && CurrentTextBox.createTextRange)
	{
		CurrentSelection = document.selection;
		if (CurrentSelection)
		{
			FullRange = CurrentTextBox.createTextRange();
			LocationIndex = FullRange.text.length;
		}
	}
	return LocationIndex;
}

function keyRestricted(CurrentTextBox, evt, maxlength, flag)
{
	var theEvent = evt || window.event;
	var key = theEvent.keyCode || theEvent.which;
	var keychar = String.fromCharCode(key);
	
	if ((key == 8 || key == 27 || key == 46 || key == 37 || key == 39 ) ) // backspace delete  escape arrows
	{
		if(GetCursorLocation(CurrentTextBox) <= maxlength && (key == 8 || key == 37))
		{
			theEvent.returnValue = false;//for IE
			if (theEvent.preventDefault) theEvent.preventDefault();//Firefox
		}
		else if(key == 46)
		{
			if(GetCursorLocation(CurrentTextBox) < maxlength)
			{
				theEvent.returnValue = false;//for IE
				if (theEvent.preventDefault) theEvent.preventDefault();//Firefox
			}
		}
	}
	else
	{
		if(GetCursorLocation(CurrentTextBox) < maxlength && !(key == 116 || key == 9 || key == 35))
		{
			theEvent.returnValue = false;//for IE
			if (theEvent.preventDefault) theEvent.preventDefault();//Firefox
		}
		else if(flag)
		{
			var exp = /[^\d-]/g;
			var txt = CurrentTextBox.value.substring(0, maxlength);
			var text = CurrentTextBox.value.substring(maxlength, CurrentTextBox.value.length);
			
			if(text.match(exp))
			{
				txt = CurrentTextBox.value.substring(0, CurrentTextBox.value.length-1);
				CurrentTextBox.value = txt;
			}
			// CurrentTextBox.value = CurrentTextBox.value.replace(exp,'');
		}
	}
}

//date picker operation....
function selected(cal, date)
{
    cal.sel.value = date;
    if (cal.dateClicked )
        cal.callCloseHandler();
}

function closeHandler(cal)
{
    cal.hide();
    _dynarch_popupCalendar = null;

}

function isArray(obj){return(typeof(obj.length)=="undefined")?false:true;}

function showCalendar(img, id, format, showsTime, showsOtherMonths)
{
    var el = document.getElementById(id);

    if (_dynarch_popupCalendar != null)
    {
        _dynarch_popupCalendar.hide();               
    } 
    else
    {
        var cal = new Calendar(1, null, selected, closeHandler);
        if (typeof showsTime == "string") 
        {
            cal.showsTime = true;
            cal.time24 = (showsTime == "24");
        }

        if (showsOtherMonths) 
        {
            cal.showsOtherMonths = true;
        }

        _dynarch_popupCalendar = cal;
        cal.setRange(1900, 2070);
        cal.create();
    }

    _dynarch_popupCalendar.setDateFormat(format);
    _dynarch_popupCalendar.parseDate(el.value);

    _dynarch_popupCalendar.sel = el;

    _dynarch_popupCalendar.showAtElement(img, "Br");
}

function get_age(born, now) {
	var birthday = new Date(now.getFullYear(), born.getMonth(), born.getDate());
	if (now >= birthday) 
		return now.getFullYear() - born.getFullYear();
	else
		return now.getFullYear() - born.getFullYear() - 1;
}

function CalAge(mnth, days, yrs)
{
    var now = new Date();
    var mm = mnth;
    var dd = days;
    var yy = yrs;
    bDay = dd + "/" + mm + "/" + yy;
	// alert(bDay);
	
    bD = bDay.split('/');
    if (bD.length == 3)
    {
        born = new Date(bD[2], bD[1] * 1 - 1, bD[0]);
        // alert(now.getTime()+" - "+born.getTime());

        years = Math.floor((now.getTime() - born.getTime()) / (365.25 * 24 * 60 * 60 * 1000));
        // alert(years);

        return years;
        /*if (years < 18)
            alert(“You are not eligible”);
        else if (years = 18 || years > 18)
            alert(“Welcome”);*/
    }
    return "";
}

function CalYearfrmAge(age, ctrl, script)
{
    var now = new Date();
    var yy = now.getFullYear();
	
	if(age != "")
	{
		age = yy - age;
		$(ctrl).val('01-01-'+age);
		// return age;
	}
	/*else
		return "";*/
}

function date_interval(mnth, days, yrs, interval, mode, dt_fmt)
{
    var now = new Date();
    var mm = mnth;
    var dd = days;
    var yy = yrs;

    if(mode == 1)
            dd += interval;
    else if(mode == 2)
            dd += (interval*7);
    else if(mode == 3)
            mm += interval;
    else if(mode == 4)
            yy += interval;

    bDay = dd + "/" + mm + "/" + yy;
    bD = bDay.split('/');
    if (bD.length == 3)
    {
        born = new Date(bD[2], bD[1] * 1 - 1, bD[0]);
        // years = Math.floor((now.getTime() + born.getTime()));
        years = dateFormat(born, dt_fmt);
        return years;
    }
    return "";
}

function select_checked(option,values,opt)
{
    var x = "";
    if(opt == '')
    {
        
        x = document.getElementById(option);
        for (var j=0;j<x.length;j++)
        {
            if(x.options[j].value != '' && x.options[j].value == values)
                    break;
        }
        document.getElementById(option).selectedIndex = j;
    }
    else
    {
        x = document.getElementsByName(option);
        for (i = 0; i < x[0].options.length; i++)
        {
            if(x[0].options[i].value != '' && x[0].options[i].value == values)
                break;
        }
        x[0].options[i].selected = 'selected';
    }
}

function SetChecked(val, ctrlname, frmname)
{
    ptr = frmname;
    len = ptr.elements.length;
    var i=0;
    for(i=0; i<len; i++)
        if(ptr.elements[i].name == ctrlname)
            ptr.elements[i].checked = val;
}

function checkbox_count(ctrlname)
{
    var checkboxes = 0;
    $('input[type=checkbox]').each(function(index, val)
    {
        if ($(this).attr('id') == ctrlname) {
            checkboxes++;
        }
    });
    return checkboxes;
}

function checkbox_chk_count(ctrlname, type)
{
    var checkboxes = 0;
    $('input[type=checkbox]:checked').each(function(index, val)
    {
        if ($(this).attr(type) == ctrlname) {
            checkboxes++;
        }
    });
    return checkboxes;
}

function ValidDate(oObject, value)
{
    var str_regexp = /([1-9][0-9]{3})-(0[1-9]|1[0-2])-([0-2][0-9]|3[0-1])/; 
    var pattern = new RegExp(str_regexp);

    var rev_str_regexp = /([0-2][0-9]|3[0-1])-(0[1-9]|1[0-2])-([1-9][0-9]{3})/; 
    var rev_pattern = new RegExp(rev_str_regexp);
    
    var date_array = "";
    var day = "";
    var month = "";
    var year = "";
    
    if ((value.match(rev_pattern)!=null)) 
    {
        date_array = value.split('-'); 
        day = date_array[0]; 
        month = date_array[1]; 
        year = date_array[2]; 
    }
    else if ((value.match(pattern)!=null)) 
    {
        date_array = value.split('-'); 
        day = date_array[2]; 
        month = date_array[1]; 
        year = date_array[0]; 
    }

    if ((value.match(pattern)!=null) || (value.match(rev_pattern)!=null)) 
    {
        var currentTime = new Date();
        var cur_month = currentTime.getMonth();
        var cur_day = currentTime.getDate();
        var cur_year = currentTime.getFullYear();

        currentTime = new Date(cur_year, cur_month, cur_day);
        var dateObj = new Date(year,(month-1),day);

        if(dateObj > currentTime)
        {
            return false;
        } 
        else
        {
            str_regexp = /^01|03|05|07|08|10|12$/; 
            pattern = new RegExp(str_regexp); 

            if ( day <= 31 && (month.match(pattern)!=null)) 
            { 
                    return true; 
            } 
            str_regexp = /^04|06|09|11$/; 
            pattern = new RegExp(str_regexp); 
            if ( day <= 30 && (month.match(pattern)!=null)) 
            { 
                    return true; 
            } 
            if (day == 29 && month == 2 && (year % 4 == 0)) 
            { 
                    return true; 
            } 
            if (day <= 28 && month == 2) 
            { 
                    return true; 
            }
        }
    }

    window.alert('Date is not valid!'); 
    oObject.focus(); 
    return false; 
}

// function Date_Compare(SDate, EDate, fmt)
function Date_Compare(SDate, EDate, fmt)
{
    var str_regexp = /([1-9][0-9]{3})-(0[1-9]|1[0-2])-([0-2][0-9]|3[0-1])/; 
    var pattern = new RegExp(str_regexp);
	
    var str_regexp_rev = /(0[1-9]|1[0-2])-([0-2][0-9]|3[0-1])-([1-9][0-9]{3})/; 
    var pattern_rev = new RegExp(str_regexp_rev);

    var rev_str_regexp = /([0-2][0-9]|3[0-1])-(0[1-9]|1[0-2])-([1-9][0-9]{3})/; 
    var rev_pattern = new RegExp(rev_str_regexp);
    
    var date_array = "";
    var day = "";
    var month = "";
    var year = "";
	
	// alert(fmt);
    var rev_pattern_flg = true;
    var pattern_flg = true;
    var pattern_rev_flg = true;
	
	if(fmt == 'mm-dd-yyyy')
	{
		rev_pattern_flg = false;
		pattern_flg = false;
		pattern_rev_flg = true;
	}
	else if(fmt == 'dd-mm-yyyy')
	{
		rev_pattern_flg = true;
		pattern_flg = false;
		pattern_rev_flg = false;
	}
	else if(fmt == 'yyyy-mm-dd')
	{
		rev_pattern_flg = false;
		pattern_flg = true;
		pattern_rev_flg = false;
	}
    
    if (SDate.match(rev_pattern)!=null && rev_pattern_flg)
    {
        date_array = SDate.split('-');
        d1 = date_array[0];
        m1 = date_array[1];
        y1 = date_array[2];
    }
    else if (SDate.match(pattern_rev)!=null && pattern_rev_flg)
    {
        date_array = SDate.split('-');
        d1 = date_array[1];
        m1 = date_array[0];
        y1 = date_array[2];
    }
    else if (SDate.match(pattern)!=null && pattern_flg)
    {
        date_array = SDate.split('-');
        d1 = date_array[2];
        m1 = date_array[1];
        y1 = date_array[0];
    }
	
    if (EDate.match(rev_pattern)!=null && rev_pattern_flg)
    {
        date_array = EDate.split('-');
        d2 = date_array[0];
        m2 = date_array[1];
        y2 = date_array[2];
    }
    else if (EDate.match(pattern_rev)!=null && pattern_rev_flg)
    {
        date_array = EDate.split('-');
        d2 = date_array[1];
        m2 = date_array[0];
        y2 = date_array[2];
    }
    else if (EDate.match(pattern)!=null && pattern_flg)
    {
        date_array = EDate.split('-');
        d2 = date_array[2];
        m2 = date_array[1];
        y2 = date_array[0];
    }

    var SDateFull = y1 + "/" + m1 + "/" +d1;
    var EDateFull = y2 + "/" + m2 + "/" +d2;
	
	// alert(SDateFull+" "+EDateFull);
	
    var startDate = new Date(SDateFull);
    var endDate = new Date(EDateFull);
	
	// alert(startDate+" "+endDate);

    if(startDate >= endDate)
        return true;
    else
        return false;
}

function val_chk_box(init, val, id)
{
    ctrl_chk_id = init+id
    if(val)
        val = 1;
    else
        val = 0;
    $("#"+ctrl_chk_id).val(val);
}
		
function arr_id_change(ctrl_name)
{
    var str_len = (ctrl_name.length-2);
    var x = document.getElementsByName(ctrl_name);
    var x_len = x.length;

    j = 1;
    for(i=0; i<x_len; i++)
    {
        x[i].id = x[i].id.substring(0, str_len);
        // x[i].id = x[i].id+"_"+i;
        x[i].id = x[i].id+j;
        j++;
    }
}
		
function arr_id_change_zero(ctrl_name)
{
    var str_len = (ctrl_name.length-2);
    var x = document.getElementsByName(ctrl_name);
    var x_len = x.length;

    j = 0;
    for(i=0; i<x_len; i++)
    {
        x[i].id = x[i].id.substring(0, str_len);
        // x[i].id = x[i].id+"_"+i;
        x[i].id = x[i].id+j;
        j++;
    }
}

function open_frame(url)
{
    $("#light").show();
    $("#fade").show();
    $(".black_overlay").height($(document).height());
    $("#iframe_div").attr("src", url);
}

function set_size(ht, width)
{
    $("#light").height(ht);
    $("#light").width(width*1.5);
    // $("#light").height(550);
    // $("#light").width(1000);
    $("#light").css("left", '21%');
    $("#light img").css("margin-left", ($("#light").width()-40));
}

function close_frame()
{
    $("#iframe_div").attr("src", "");
    $("#light").height("");
    $("#light").width("");
    $("#light").hide();
    $("#fade").hide();
}

function print_box()
{
    // "print_box"
    if(window.print())
    {
        self.close();
    }
    else
    {
        $("#print_box").hide();
    }
}

// function form_action_load(SCRIPT_NAME,main,title,action,id)
function form_action_load(SCRIPT_NAME,page,action,id)
{
    // url = SCRIPT_NAME+'?page='+main+'&module='+title;
    url = SCRIPT_NAME;
	
    if(page != "")
        url += '?page='+page;
    if(action != "view" && action != "")
        url += '&mode='+action;

    var action1 = action.toLowerCase();
    if(action1 == 'delete')
    {
        say = confirm("Are you sure you want to delete this record?");
    }
    else
        say = true;
    
    if(id != 0)
        url += '&id='+id;
    
    if(say)
        window.location.href = url;
}

function clear_form_elements(page)
{
    $('#delete_img').hide();
	// location.reload();
	if(page == "msm_screening" || page == "idu_screening" || page == "recuirtment")
		page = "msm_introduction";
	
	window.location.href = "index.php?page="+page;
	return true;
	
    /*if(page == 'recuirtment')
    {
        $('#id').val('');
        $('#participant_div').hide();
        ele = '#recuirtment';
    }*/
    if(page == 'survey_master' || page == 'main_menu' || page == 'sub_menu')
    {
        $('#id').val('');
        ele = '#survey';
    }
    if(page == 'locator_info')
    {
        $('#id').val('');
        ele = '#recuirtment';
    }
    if(page == 'lab_mapping' || page == 'reimbusmnt_mapping' || page == 'lab_master' || page == 'reimbusmnt_master' || page == 'incentive_master' || page == 'usr_mngmnt' || page == 'lab_test_master' || page == 'loc_master' || page == 'specimen_master' || page == 'recuirtment' || page == 'app_settings' || page == 'loc_mapping')
    {
        location.reload();
        return true;
    }
    
    $(ele).find(':input').each(function() {
        switch(this.type)
        {
            case 'password':
            case 'select-multiple':
            case 'select-one':
            case 'text':
            case 'textarea':
                $(this).val('');
                break;
            case 'checkbox':
            case 'radio':
                this.checked = false;
        }
    });
}

function getUrlVars()
{
        var vars = [], hash;
        var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
        for(var i = 0; i < hashes.length; i++)
        {
                hash = hashes[i].split('=');
                vars.push(hash[0]);
                vars[hash[0]] = hash[1];
        }
        return vars;
}

function get_location(surveyid, attr, flag)
{
	var url = "";
	var loc = window.location;
	var pathName = loc.pathname.substring(0, loc.pathname.lastIndexOf('/') + 1);
	url = loc.href.substring(0, loc.href.length - ((loc.pathname + loc.search + loc.hash).length - pathName.length));
	
	$.ajax({
		type: "POST",
		data: "surveyid="+surveyid+"&attr="+attr,
		url: url+"getlocation.php",
		error: function(msg){
			alert( msg.status );
		},
		success: function(msg){
			if(msg != "")
			{
				if(flag)
				{
					if(attr == "location")
					{
						$('#location').val(msg);
						select_checked('location_sel', msg, "");
						// $('#cupn_cde').val(msg);
					}
					if(attr == "location_coupon")
					{
						var msg = msg.split(" ");
						$('#location').val(msg[0]);
						select_checked('location_sel', msg[0], "");
						if(msg[1] == "Y")
							$('#location_sel').attr("disabled", true);
						else
							$('#location_sel').attr("disabled", false);
							// $('#location_sel').removeAttr("disabled");
							
						// $('#cupn_cde').val(msg[0]);
					}
				}
			}
			/*close_frame();
			$('#tabs-1').html(msg);
			$("#delete_img").show();*/
		}
	});
}

function inArray(needle, haystack) {
    var length = haystack.length;
    for(var i = 0; i < length; i++) {
        if(haystack[i] == needle) return true;
    }
    return false;
}

function find_index(array, string)
{
    var i = 0;
    for(i=0;i<array.length;i++) {
		if(array[i]==string) break;
    }
    return array[i] == string ? i : -1;
}
     
function array_unique(array_to_modify, remove_empty_items)
{
    new_array = [];
    for(var i=0;i<array_to_modify.length;i++)
	{
    if(find_index(new_array, array_to_modify[i])==-1&&((remove_empty_items&&remove_empty_items==true&&array_to_modify[i].toString().replace(/\s/g, '')!='')||!remove_empty_items))
		new_array[new_array.length] = array_to_modify[i];
    }
    return new_array;
}