/*
 * LawLogix utility - jQuery plugin
 * 
 * Copyright(c) 2010, LawLogix Group Inc
 * Change History:
 *	B08018 NR 11/29/2010
 *	BUG B09126 JM 02/22/2011 (changed edge alert duration from 3 to 6)
 *  BUG B09997 GJM 06/16/2011
 *  BUG B10035 GJM 06/21/2011
 *  BUG B10328 NR 08/04/2011 changed attr disable '' to disable False. this stop working since upgrade to 1.6
 */
 
/*	
 * Check/Uncheck checkbox for group of checkbox. 
 * Class name needs to be specified.
 * ie) to call it: onclick="checkAllByClass($j(this),'CheckMe','check-only', true)"
 * checkbox should have: class="CheckMe otherClass"
 * params: 3rd param [check-only | uncheck-only | both] 
 * B04488 NR 06/24/2010
 * 
 */
function checkAllByClass(baseChkBoxObj, className,sToggle,bDisableWhenChecked){
	if (baseChkBoxObj.attr('checked')){
        if(sToggle != 'uncheck-only'){
            $j("."+className).attr('checked', true);
        }        
        if(bDisableWhenChecked){
            $j("."+className).attr("disabled",true);  /* BUG B10328 NR 08/04/2011 */
        }
	}else{
        if(sToggle != 'check-only'){
            $j("."+className).attr({'checked':false });
        } 
        if(bDisableWhenChecked){
            $j("."+className).attr("disabled",false);    /* BUG B10328 NR 08/04/2011 */
        }
	}
}

/*
* Pass this function an ID of a div (maybe other elements too depending on browser)
* This will hide/show the element whose ID you pass in, helpful when its not just
* the next element on a page but something random, or programmatically in a for
* loop to a bunch of ID's in an array for a "hide all" type of thing
* JV 07/16/2010
*/
function toggle_id(daID){
	var daVal;
	daVal = document.getElementById(daID);
	$j(daVal).toggle('blind');
}

/*
* Clicking a collapse_head class element, will toggle visibility of the following collapse_body
* class element.
* JV 07/16/2010
*/
jQuery(document).ready(function(){
	$j(".collapse_head").click(function(){
		$j(this).next(".collapse_body").slideToggle(600);
	});
});

/*
* Pass in the name of the cookie to this function, to have it parse the cookie and toggle(collapse)
* the ID's designated by the cookie
* JV 07/20/2010
*/
function CookieCollapseToggle(name){
	var cookie;
	var i;
	cookie = readCookie(name);
	if(cookie!= null){
		var arrText = cookie.split("|");
		for ( i=0; i < arrText.length;i++){
			toggle_id(arrText[i]);
		}
	}
}
	
/*
* Pass in the name of the cookie you want to save to, and an array of ID's assigned to collapse_body
* elements and it will create a cookie of which sections are collapsed.
* JV 07/20/2010
*/
function setCookieCollapse(name, arr){
	var daCookieVal;
	var daID;
	var daVal;
	var i;
	daCookieVal="";
	daID="";
	for(i=0; i< arr.length; i++){
		daVal = document.getElementById(arr[i]);
		if(daVal.style.display=="none"){
			daCookieVal=daCookieVal+"|"+arr[i];
		}
	}
	createCookie(name,daCookieVal,7);
}
			
/*
* show jquery themed alert for 6 sec
* B08018 NR 11/29/2010 
* BUG B09126 JM 02/22/2011
*/		
edge_alert = function(msg){
	/*create erro message*/
	$j('#edge_warning_msg').html(msg);
	window.scrollTo(0,0)
	$j('#edge_warning').fadeIn('slow').delay(6000).fadeOut('slow');
}


/*
*Hotkeys
*BUG B09614 JV 04/21/2011
*BUG B09614 JV 04/28/2011 admin, billing, privs
*BUG B09614 JV 04/28/2011 body check
*/
	jQuery(document).ready(function() {
		var isCtrl = false; 
		var OSName="Unknown OS";
		if (navigator.appVersion.indexOf("Win")!=-1) {
			OSName="Windows";
		}
		else if (navigator.appVersion.indexOf("Mac")!=-1){ 
			OSName="MacOS";
		}

    	jQuery(document).keydown(function (e) {
        		/*alert(OSName);
        		alert(e.ctrlKey);
        		alert(e.altKey);*/
        		if(daJSON_HTKObject.Enabled==true){
                	if(((e.ctrlKey==true) & (OSName=="MacOS")) | ((e.ctrlKey==true) & (e.altKey==true) & (OSName=="Windows"))){
                		var actualkey = String.fromCharCode(e.keyCode).toLowerCase();
                		/*update info*/
                		daHotKey=daJSON_HTKObject.Save.value;
						if(actualkey == daHotKey.toLowerCase()) {
                			/*alert('Save');*/
                			e.preventDefault();
                			$j('input[value="Update Info"]:first').click();
                		}
                		/*cancel*/
                		daHotKey=daJSON_HTKObject.Cancel.value;
						if(actualkey == daHotKey.toLowerCase()) {
                			/*alert('Cancel');*/
                			e.preventDefault();
                			$j('input[value="Cancel"]:first').click();
                		}
                		
                		if(top.frames['Body']){
                			/*Reports*/
                			var daHotKey=daJSON_HTKObject.Reports.value;
                			var dahref = daJSON_HTKObject.Reports.href;
							if(actualkey == daHotKey.toLowerCase()) {
                				/*alert('Reports');*/
                				e.preventDefault();
                				if(daJSON_HTKObject.ReportPriv==true){
                					if(daJSON_HTKObject.newWindow){
                						window.open(dahref, 'MReports');
                					}else{
                						top.frames['Body'].location.href = dahref;
                					}
                				}
                			}
                			/*Messages, Only new window*/
                			daHotKey=daJSON_HTKObject.Messages.value;
                			dahref = daJSON_HTKObject.Messages.href;
							if(actualkey == daHotKey.toLowerCase()) {
                				/*alert('Messages');*/
                				e.preventDefault();
                				window.open(dahref,'Messaging','width=920, height=707,  scrollbars=yes, resizable=no, toolbar=yes');
                			}
                			/*Reminder list, Never new window*/
                			daHotKey=daJSON_HTKObject.Reminders.value;
                			dahref = daJSON_HTKObject.Reminders.href;
							if(actualkey == daHotKey.toLowerCase()) {
                				/*alert('Reminders');*/
                				e.preventDefault();
                				top.frames['Body'].location.href = dahref;
                			}
                			/*Dashboard, Only new window*/
                			daHotKey=daJSON_HTKObject.Dashboard.value;
                			dahref = daJSON_HTKObject.Dashboard.href;
							if(actualkey == daHotKey.toLowerCase()) {
                				/*alert('Dashboard');*/
                				e.preventDefault();
                				window.open(dahref, 'Dashboard', 'width=1000, height=800,  scrollbars=yes, resizable=yes, toolbar=yes');
                			}
                			/*Calendar*/
                			daHotKey=daJSON_HTKObject.Calendar.value;
                			dahref = daJSON_HTKObject.Calendar.href;
                			if(actualkey == daHotKey.toLowerCase()) {
                				/*alert('Calendar');*/
                				e.preventDefault();
                				if(daJSON_HTKObject.newWindow){
                					window.open(dahref, 'Calendar');
                				}else{
                					top.frames['Body'].location.href = dahref;
                				}
                			}
                			/*FN individual,Never new window*/
                			daHotKey=daJSON_HTKObject.FNIndividual.value;
                			dahref = daJSON_HTKObject.FNIndividual.href;
							if(actualkey == daHotKey.toLowerCase()) {
                				/*alert('FNIndividual');*/
                				e.preventDefault();
                				top.frames['Body'].location.href = dahref;
                			}
                			/*Casenotes*/
                			daHotKey=daJSON_HTKObject.CaseNotes.value;
                			dahref = daJSON_HTKObject.CaseNotes.href;
                			if(actualkey == daHotKey.toLowerCase()) {
                				/*alert('Casenotes');*/
                				e.preventDefault();
                				if(daJSON_HTKObject.newWindow){
                					window.open(dahref, 'CaseNote');
                				}else{
                					top.frames['Body'].location.href = dahref;
                				}
                			}
                			/*Address Book*/
                			daHotKey=daJSON_HTKObject.AddressBook.value;
                			dahref = daJSON_HTKObject.AddressBook.href;
                			if(actualkey == daHotKey.toLowerCase()) {
                				/*alert('AddressBook');*/
                				e.preventDefault();
                				if(daJSON_HTKObject.newWindow){
                					window.open(dahref, 'AddressBook');
                				}else{
                					top.frames['Body'].location.href = dahref;
                				}
                			}
                			/*Company, Never new window*/
                			daHotKey=daJSON_HTKObject.Company.value;
                			dahref = daJSON_HTKObject.Company.href;
							if(actualkey == daHotKey.toLowerCase()) {
                				/*alert('Company');*/
                				e.preventDefault();
                				top.frames['Body'].location.href = dahref;
                			}
                			/*Billing, Never new window*/
                			daHotKey=daJSON_HTKObject.Billing.value;
                			dahref = daJSON_HTKObject.Billing.href;
							if(actualkey == daHotKey.toLowerCase()) {
                				/*alert('Company');*/
                				e.preventDefault();
                				if(daJSON_HTKObject.BillingPriv==true){
                					top.frames['Body'].location.href = dahref;
                				}
                			}
                			/*Edit Document Templates, Only new window*/
                			daHotKey=daJSON_HTKObject.Template.value;
                			dahref = daJSON_HTKObject.Template.href;
							if(actualkey == daHotKey.toLowerCase()) {
                				/*alert('Template');*/
                				e.preventDefault();
                				if(daJSON_HTKObject.TemplatePriv==true){
                					window.open(dahref, 'editdocumenttemplate', 'width=1000, height=800,  scrollbars=yes, resizable=yes, toolbar=yes');
                				}
                			}
                			/*Logout, Never new window*/
                			daHotKey=daJSON_HTKObject.Logout.value;
                			dahref = daJSON_HTKObject.Logout.href;
							if(actualkey == daHotKey.toLowerCase()) {
                				/*alert('Logout');*/
                				e.preventDefault();
                				top.location.href = dahref;
                			}
                			/*Admin, Never new window*/
                			daHotKey=daJSON_HTKObject.Admin.value;
                			dahref = daJSON_HTKObject.Admin.href;
							if(actualkey == daHotKey.toLowerCase()) {
                				/*alert('Company');*/
                				e.preventDefault();
                				if(daJSON_HTKObject.AdminPriv==true){
                					top.frames['Body'].location.href = dahref;
                				}
                			}
                		}/*if body exists end*/
                	}/*if ctrl is true end*/
                }/*if enabled*/
          });
     });
     
     
     
     
    
$j(function(){
	// disabling datepicker try to render by checking offset and decide to display above/below. this is not quite working elegantly. hopefully we can enable in later version.
	// with this disabled, it always displayed below the input
	/*$j.extend($j.datepicker,{_checkOffset:function(inst,offset,isFixed){return offset}});*/
	// Datepicker
	$j('.datepicker').datepicker({
			showOn: 'button',
			buttonImage: '/Extras/jquery-ui/css/'+jQueryUI_Theme+'/Images/calpick.png',
			buttonImageOnly: true,
			showAnim:'fadeIn', //default is cool but looks so annoying on IE hence changed
			changeMonth: true,
			changeYear: true,
			constrainInput: false,
			'onClose': function(){
				$j(this).focus();
			},
			beforeShow: function(input, inst){
					inst.dpDiv.css({bottom: 'auto',top: 'auto',right:'auto',left:'auto'});
					var offset=$j(input).offset();
					offsetNum=$j(document).height()-$j(input).height()-offset.top;
					if (offsetNum<200){
						setTimeout(function(){
							inst.dpDiv.css({bottom: '0px',top: 'auto'});
						},0);
					}
					offsetNum=$j(document).width()-$j(input).width()-offset.left;
					if (offsetNum<250){
						setTimeout(function(){
							inst.dpDiv.css({right: '0px',left: 'auto'});
						},0);
					}
					if($j(input).is(':disabled')){
						setTimeout(function(){
							inst.dpDiv.css({left: '-1000px',right: 'auto'});
						},0);
					}
			}
		});
	/*
		If you edit the bindDatePicker function, please copy/paste function into handleFinalI94.js as well.
	*/
	function bindDatePicker(){
		$j('.datepicker').bind("dblclick", function(){
			var datToday;
			datToday = new Date();
			var intInsertDay = datToday.getDate();
			var intInsertMonth = datToday.getMonth()+1;
			var intInsertYear = datToday.getFullYear();
			$j(this).val(intInsertMonth.toString()+"/"+intInsertDay.toString()+"/"+intInsertYear.toString());
		});
		$j('.datepicker').bind("blur", function(){
			var daDate = $j(this).val();
			/*B08559 JV 11/22/2010 ----------START---------- */
			if(daDate.toLowerCase() == "t"){
				var currentTime = new Date();
				var month = currentTime.getMonth() + 1;
				var day = currentTime.getDate();
				var year = currentTime.getFullYear();
				daDate= month + "/" + day + "/" + year;
			}else if(daDate.substring(0,1) == "+"){
				var currentTime = new Date();
				var month = currentTime.getMonth() + 1;
				var day = currentTime.getDate();/* + parseInt(daDate.substring(1));*/
				var year = currentTime.getFullYear();
				/*daDate= month + "/" + day + "/" + year;*/
				daDate = dateAdd("d",daDate.substring(1), month + "/" + day + "/" + year);
				month = daDate.getMonth() + 1;
				day = daDate.getDate();
				year = daDate.getFullYear();
				daDate= month + "/" + day + "/" + year;
			}else if(daDate.substring(0,1) == "-"){
				var currentTime = new Date();
				var month = currentTime.getMonth() + 1;
				var day = currentTime.getDate();/* - parseInt(daDate.substring(1));*/
				var year = currentTime.getFullYear();
				/*daDate= month + "/" + day + "/" + year;*/
				daDate = dateAdd("d",-parseInt(daDate.substring(1)), month + "/" + day + "/" + year);
				month = daDate.getMonth() + 1;
				day = daDate.getDate();
				year = daDate.getFullYear();
				daDate= month + "/" + day + "/" + year;
			}
	
			/*B08559 JV 11/22/2010 ----------END---------- */
			if((daDate !="") & (daDate!="00/00/00") & (daDate.toLowerCase() != "d/s")){ /*BUG B08507 JV 11/11/2010 */
				var daCheck = !isNaN(new Date(daDate));
				daDate = daDate.replace(/-/g,"/");
				var arrDate=daDate.split("/");
				var dYear=arrDate[arrDate.length-1];
				if ((dYear.length==2) && (arrDate.length==3)){ /* BUG B08294 NR 10/11/2010  ---------- BEGIN ---------- */
					dYear = '20' + dYear;
					daDate = arrDate[0] + '/' + arrDate[1] + '/' + dYear;
					$j(this).val(daDate);
				}
				if(dYear.length<4 || arrDate.length<3){
					daCheck= false;
				}else{
					var dMonth=arrDate[0];
					var dDays=arrDate[1];
					if(dMonth>12 || dMonth<1 || dDays>31 || dDays<1){
						daCheck= false;
					}
				}
	
	
				if(daCheck==false){
	
					var daContent ="Invalid Date Format: "+daDate+"&nbsp;&nbsp;&nbsp;&nbsp;Date Format: MM/DD/YYYY or D/S<p></p><p></p>";
					$j('#datePickerError').remove();
					if(document.getElementById('datePickerError')==null){
						$j(this).after("<span id='datePickerError' style='color:red; padding:1em 1em;'>"+daContent+"</span>");
					}
					jQuery('#datePickerError').dialog({
											modal:false,
											autoOpen:true,
											//show:'slide', BUG B09524 JPU 04/08/2011
											title:'Invalid Date',
											minWidth:450,
											position:'top',
											buttons:{"Ok":function() { jQuery(this).dialog("close");}}
											});
				setTimeout(function(){ $j('#datePickerError').dialog('destroy')},5000);
	
	
				}
			}
		});
	}//end bind datepicker
	
	bindDatePicker();

	/* Format file upload inputs  BUG B09398 GJM 03/22/2011 (commented out section)
	$j('input:file').each(function(){
		var uploadbuttonlabeltext = $j(this).attr('title');
		if(uploadbuttonlabeltext == ''){
			var uploadbuttonlabeltext = 'Browse';
		}

		var uploadbutton = "&nbsp;<input type='button' value='Browse' />";
		$j(this).wrap("<div class='fileinputs'></div>");
		$j(this).addClass("file").css("opacity", 0);
		$j(this).parent().append($j("<div class='fakefile' />").append($j("<input type='text' />").attr("id",$j(this).attr("id")+"__fake")).append(uploadbutton));
		$j(this).bind("change", function() {
			var tempUploadVal=$j(this).val();
			tempUploadVal=tempUploadVal.replace("C:\\fakepath\\","");
			$j("#"+$j(this).attr("id")+"__fake").val(tempUploadVal);
		});
		$j(this).bind("mouseout", function() {
			$j("#"+$j(this).attr("id")+"__fake").val($j(this).val());;
		});
	});*/

	// autocomplete BUG B09343 JPU 03/14/11
	var arrCountries = ["UNITED STATES OF AMERICA","AFGHANISTAN","ALBANIA","ALGERIA","ANDORRA","ANGOLA","ANGUILLA","ANTIGUA AND BARBUDA","ARGENTINA","ARMENIA","ARUBA","AUSTRALIA","AUSTRIA","AZERBAIJAN","BAHAMAS","BAHRAIN","BANGLADESH","BARBADOS","BELARUS","BELGIUM","BELIZE","BENIN","BERMUDA","BHUTAN","BOLIVIA","BOSNIA AND HERZEGOVINA","BOTSWANA","BRAZIL","BRITISH VIRGIN ISLANDS","BRUNEI","BULGARIA","BURKINA FASO","BURMA (MYANMAR)","BURUNDI","CAMBODIA","CAMEROON","CANADA","CAPE VERDE","CAYMAN ISLANDS","CENTRAL AFRICAN REPUBLIC","CHAD","CHILE","CHINA","COLOMBIA","COMOROS","CONGO (BRAZZAVILLE)","CONGO (KINSHASA)","COSTA RICA","COTE D'IVOIRE","CROATIA","CUBA","CYPRUS","CZECH REPUBLIC","CZECHOSLOVAKIA","DENMARK","DEPENDANT TERRITORY","DJIBOUTI","DOMINICA","DOMINICAN REPUBLIC","EAST TIMOR","ECUADOR","EGYPT","EL SALVADOR","EQUATORIAL GUINEA","ERITREA","ESTONIA","ETHIOPIA","FIJI","FINLAND","FRANCE","FRENCH POLYNESIA","GABON","GAMBIA","GEORGIA","GERMANY","GHANA","GIBRALTAR","GREECE","GREENLAND","GRENADA","GUATEMALA","GUINEA","GUINEA-BISSAU","GUYANA","HAITI","HOLY SEE","HONDURAS","HONG KONG","HUNGARY","ICELAND","INDIA","INDONESIA","IRAN","IRAQ","IRELAND","ISRAEL","ITALY","IVORY COAST","JAMAICA","JAPAN","JORDAN","KAZAKHSTAN","KENYA","KIRIBATI","KOSOVO","KUWAIT","KYRGYZSTAN","LAOS","LATVIA","LEBANON","LESOTHO","LIBERIA","LIBYA","LIECHTENSTEIN","LITHUANIA","LUXEMBOURG","MACAU (SAR)","MACEDONIA","MADAGASCAR","MALAWI","MALAYSIA","MALDIVES","MALI","MALTA","MARSHALL ISLANDS","MAURITANIA","MAURITIUS","MEXICO","MICRONESIA","MOLDOVA","MONACO","MONGOLIA","MONTSERRAT","MONTENEGRO","MOROCCO","MOZAMBIQUE","NAMIBIA","NAURU","NEPAL","NETHERLANDS","NETHERLANDS ANTILLES","NEW ZEALAND","NICARAGUA","NIGER","NIGERIA","NIUE","NORTH KOREA","NORWAY","OMAN","PAKISTAN","PALAU","PALESTINE","PALESTINIAN TERRITORIES","PANAMA","PAPUA NEW GUINEA","PARAGUAY","PERU","PHILIPPINES","PITCAIRN ISLANDS","POLAND","PORTUGAL","QATAR","REPUBLIC OF CONGO","ROMANIA","RUSSIA","RWANDA","SAINT KITTS AND NEVIS","SAINT LUCIA","SAINT VINCENT AND THE GRENADINES","SAMOA","SAN MARINO","SAO TOME AND PRINCIPE","SAUDI ARABIA","SENEGAL","SERBIA","SEYCHELLES","SIERRA LEONE","SINGAPORE","SLOVAKIA","SLOVENIA","SOLOMON ISLANDS","SOMALIA","SOUTH AFRICA","SOUTH KOREA","SOVIET UNION","SPAIN","SRI LANKA","ST HELENA","STATELESS","SUDAN","SURINAME","SWAZILAND","SWEDEN","SWITZERLAND","SYRIA","TAIWAN","TAJIKISTAN","TANZANIA","THAILAND","TIMOR-LESTE","TOGO","TONGA","TRINIDAD AND TOBAGO","TUNISIA","TURKEY","TURKMENISTAN","TURKS AND CAICOS ISLANDS","TUVALU","UGANDA","UKRAINE","UNITED ARAB EMIRATES","UNITED KINGDOM","URUGUAY","UZBEKISTAN","VANUATU","VENEZUELA","VIETNAM","WESTERN SAMOA","YEMEN","YUGOSLAVIA","ZAMBIA","ZIMBABWE"];
	$j(".countries").autocomplete({source: arrCountries});
	$j(".jq-button").not(".ui-button").button(); //BUG B10035 GJM 06/21/2011 (keep from repeatedly adding button spans)
	$j(".jq-buttonset").buttonset();



	/*BUG B09493 JV 04/06/2011*/
	$j(document).ready(function(){
	    $j('textarea[maxlength]').keyup(function(){
	        maxLen($j(this));
	    });
	    $j('textarea[maxlength]').blur(function(){
	        maxLen($j(this));
	    });
	    $j('textarea[maxlength]').blur();

	});

	function maxLen(element){
			var $daElement=$j(element);
	        var max = parseInt($daElement.attr('maxlength'));
	        var curLen = $daElement.val().length;
	        if($daElement.parent().find('.charsRemaining').size()==0){
	        	$daElement.after("<br><span class='charsRemaining' style='color:red; padding:1em 1em;'></span>");
	        }
	        if(curLen >= max){
	            $daElement.val($daElement.val().substr(0, max));
	            $daElement.parent().find('.charsRemaining').html('You have 0 characters remaining, data may be truncated');
	        } else {
        		$daElement.parent().find('.charsRemaining').html('You have ' + (max - curLen) + ' characters remaining');
        	}
	    }






});

	/*BUG B08642 XC 04/19/2011*/

$j(document).ready(function(){
	$j(".drop").hover(
		function(){$j(this).children(".dropdown").addClass("display")},
		function(){$j(this).children(".dropdown").delay(500).removeClass("display")});

	$j(".display").hover(
		function(){$j(this).addClass("display");},
		function(){$j(this).delay(500).removeClass("display")});

	$j(".select").hover(
		function(){$j(this).addClass("ui-state-hover");},
		function(){$j(this).removeClass("ui-state-hover")});
});
  
$j(document).ready(function(){
	simple_tooltip(".tool","tooltip");
});

