/* mask input */

(function($){$.fn.caret=function(begin,end){if(this.length==0)return;if(typeof begin=='number'){end=(typeof end=='number')?end:begin;return this.each(function(){if(this.setSelectionRange){this.focus();this.setSelectionRange(begin,end);}else if(this.createTextRange){var range=this.createTextRange();range.collapse(true);range.moveEnd('character',end);range.moveStart('character',begin);range.select();}});}else{if(this[0].setSelectionRange){begin=this[0].selectionStart;end=this[0].selectionEnd;}else if(document.selection&&document.selection.createRange){var range=document.selection.createRange();begin=0-range.duplicate().moveStart('character',-100000);end=begin+range.text.length;}return{begin:begin,end:end};}};var charMap={'9':"[0-9]",'a':"[A-Za-z]",'*':"[A-Za-z0-9]"};$.mask={addPlaceholder:function(c,r){charMap[c]=r;}};$.fn.unmask=function(){return this.trigger("unmask");};$.fn.mask=function(mask,settings){settings=$.extend({placeholder:"_",completed:null},settings);var re=new RegExp("^"+$.map(mask.split(""),function(c,i){return charMap[c]||((/[A-Za-z0-9]/.test(c)?"":"\\")+c);}).join('')+"$");return this.each(function(){var input=$(this);var buffer=new Array(mask.length);var locked=new Array(mask.length);var valid=false;var ignore=false;var firstNonMaskPos=null;$.each(mask.split(""),function(i,c){locked[i]=(charMap[c]==null);buffer[i]=locked[i]?c:settings.placeholder;if(!locked[i]&&firstNonMaskPos==null)firstNonMaskPos=i;});function focusEvent(){checkVal();writeBuffer();setTimeout(function(){$(input[0]).caret(valid?mask.length:firstNonMaskPos);},0);};function keydownEvent(e){var pos=$(this).caret();var k=e.keyCode;ignore=(k<16||(k>16&&k<32)||(k>32&&k<41));if((pos.begin-pos.end)!=0&&(!ignore||k==8||k==46)){clearBuffer(pos.begin,pos.end);}if(k==8){while(pos.begin-->=0){if(!locked[pos.begin]){buffer[pos.begin]=settings.placeholder;if($.browser.opera){s=writeBuffer();input.val(s.substring(0,pos.begin)+" "+s.substring(pos.begin));$(this).caret(pos.begin+1);}else{writeBuffer();$(this).caret(Math.max(firstNonMaskPos,pos.begin));}return false;}}}else if(k==46){clearBuffer(pos.begin,pos.begin+1);writeBuffer();$(this).caret(Math.max(firstNonMaskPos,pos.begin));return false;}else if(k==27){clearBuffer(0,mask.length);writeBuffer();$(this).caret(firstNonMaskPos);return false;}};function keypressEvent(e){if(ignore){ignore=false;return(e.keyCode==8)?false:null;}e=e||window.event;var k=e.charCode||e.keyCode||e.which;var pos=$(this).caret();if(e.ctrlKey||e.altKey){return true;}else if((k>=41&&k<=122)||k==32||k>186){var p=seekNext(pos.begin-1);if(p<mask.length){if(new RegExp(charMap[mask.charAt(p)]).test(String.fromCharCode(k))){buffer[p]=String.fromCharCode(k);writeBuffer();var next=seekNext(p);$(this).caret(next);if(settings.completed&&next==mask.length)settings.completed.call(input);}}}return false;};function clearBuffer(start,end){for(var i=start;i<end&&i<mask.length;i++){if(!locked[i])buffer[i]=settings.placeholder;}};function writeBuffer(){return input.val(buffer.join('')).val();};function checkVal(){var test=input.val();var pos=0;for(var i=0;i<mask.length;i++){if(!locked[i]){while(pos++<test.length){var reChar=new RegExp(charMap[mask.charAt(i)]);if(test.charAt(pos-1).match(reChar)){buffer[i]=test.charAt(pos-1);break;}}}}var s=writeBuffer();if(!s.match(re)){input.val("");clearBuffer(0,mask.length);valid=false;}else
valid=true;};function seekNext(pos){while(++pos<mask.length){if(!locked[pos])return pos;}return mask.length;};input.one("unmask",function(){input.unbind("focus",focusEvent);input.unbind("blur",checkVal);input.unbind("keydown",keydownEvent);input.unbind("keypress",keypressEvent);if($.browser.msie)this.onpaste=null;else if($.browser.mozilla)this.removeEventListener('input',checkVal,false);});input.bind("focus",focusEvent);input.bind("blur",checkVal);input.bind("keydown",keydownEvent);input.bind("keypress",keypressEvent);if($.browser.msie)this.onpaste=function(){setTimeout(checkVal,0);};else if($.browser.mozilla)this.addEventListener('input',checkVal,false);checkVal();});};})(jQuery);


/* date extension library */

Date.is=function(Ob){try{if(typeof Ob=="object"){if(Ob.constructor==Date){return true;};};}catch(CurError){};return false;};Date.parseFormat=function(CurDate,Mask,DefaultTo){if(typeof CurDate!="string"||CurDate==""){return null;};if(typeof Mask!="string"||Mask==""){return null;};if(typeof DefaultTo!=0&&DefaultTo!=1&&DefaultTo!=2){DefaultTo=0;};var MaskChars="DMYhHmsltTz";var RegExChars="^$.*+?=!:|\\/()[]{}-";var MonthRef={jan:0,feb:1,mar:2,apr:3,may:4,jun:5,jul:6,aug:7,sep:8,oct:9,nov:10,dec:11}
var RegEx="";Mask+=" ";var DF=[null,null,null,null,null,null,null,null];var CurChar;var MaskPart="";var MaskPartCnt=1;for(var Cnt=0;Cnt<Mask.length;Cnt++){CurChar=Mask.charAt(Cnt);if((MaskChars.indexOf(CurChar)==-1)||(MaskPart!=""&&CurChar!=MaskPart.charAt(MaskPart.length-1))){if(MaskPart!=""){switch(MaskPart){case"YY":case"YYYY":DF[0]=MaskPartCnt;break;case"M":case"MM":case"MMM":case"MMMM":DF[1]=MaskPartCnt;break;case"D":case"DD":case"DDD":case"DDDD":DF[2]=MaskPartCnt;break;case"h":case"hh":case"H":case"HH":DF[3]=MaskPartCnt;break;case"m":case"mm":DF[4]=MaskPartCnt;break;case"s":case"ss":DF[5]=MaskPartCnt;break;case"l":DF[6]=MaskPartCnt;break;case"t":case"T":case"tt":case"TT":DF[7]=MaskPartCnt;break;case"z":DF[8]=MaskPartCnt;break;};switch(MaskPart){case"h":RegEx+="(1[0-2]|[1-9])";break;case"hh":RegEx+="(1[0-2]|0[1-9])";break;case"H":RegEx+="(2[0-4]|1[0-9]|[0-9])";break;case"HH":RegEx+="(2[0-4]|1[0-9]|0[0-9])";break;case"s":case"m":RegEx+="([0-5]?[0-9])";break;case"ss":case"mm":RegEx+="([0-5]?[0-9])";break;case"l":RegEx+="([0-9]+)";break;case"t":case"T":RegEx+="(a|p)";break;case"tt":case"TT":RegEx+="(am|pm)";break;case"D":RegEx+="((?:3[01])|(?:[12][0-9])|(?:0[1-9])|[1-9])";break;case"DD":RegEx+="((?:3[01])|(?:[12][0-9])|(?:0[1-9]))";break;case"DDD":RegEx+="(sun|mon|tue|wed|thu|fri|sat)";break;case"DDDD":RegEx+="(sunday|monday|tuesday|wednesday|thursday|friday|saturday)";break;case"M":RegEx+="((?:1[012])|(?:0[1-9])|[1-9])";break;case"MM":RegEx+="((?:1[012])|(?:0[1-9]))";break;case"MMM":RegEx+="(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)";break;case"MMMM":RegEx+="(january|february|march|april|may|june|july|august|september|october|november|december)";break;case"YY":RegEx+="([0-9]{2})";break;case"YYYY":RegEx+="((?:1[6-9]|[2-9][0-9])[0-9]{2})";break;case"z":RegEx+="(Z|UT|[\+\-](?:1[012]|[0]?[0-9])(?::?[0-5]?[0-9]))";break;};MaskPart="";MaskPartCnt++;};if(MaskChars.indexOf(CurChar)>-1){MaskPart=CurChar;}else{if(RegExChars.indexOf(CurChar)>=0){RegEx+="\\";};RegEx+=CurChar;};}else{MaskPart+=CurChar;};};RegEx=RegEx.substring(0,RegEx.length-1);var ParsedDF;if(ParsedDF=new RegExp("^"+RegEx+"$","i").exec(CurDate)){};if(!ParsedDF){return null};for(var Cnt=0;Cnt<DF.length;Cnt++){if(DF[Cnt]!=null){DF[Cnt]=ParsedDF[DF[Cnt]];};};if(DF[1]!=null){var CurDF=MonthRef[DF[1].substring(0,3).toLowerCase()];if(CurDF!=null){DF[1]=CurDF;}else{DF[1]=DF[1]-1;};};if(DF[7]!=null&&DF[3]!=null&&DF[3]<13){var CurAP=DF[7].substring(0,1).toLowerCase();if(CurAP=="p"){DF[3]=DF[3]+12;};};if(DefaultTo==0){}else if(DefaultTo==1){var NowDate=new Date();if(DF[0]==null){DF[0]=NowDate.getFullYear()};if(DF[1]==null){DF[1]=NowDate.getMonth()};if(DF[2]==null){DF[2]=NowDate.getDate()};if(DF[3]==null){DF[3]=NowDate.getHours()};if(DF[4]==null){DF[4]=NowDate.getMinutes()};if(DF[5]==null){DF[5]=NowDate.getSeconds()};if(DF[6]==null){DF[6]=NowDate.getMilliseconds()};}else if(DefaultTo==2){var NowDate=new Date();if(DF[0]==null){DF[0]=NowDate.getUTCFullYear()};if(DF[1]==null){DF[1]=NowDate.getUTCMonth()};if(DF[2]==null){DF[2]=NowDate.getUTCDate()};if(DF[3]==null){DF[3]=NowDate.getUTCHours()};if(DF[4]==null){DF[4]=NowDate.getUTCMinutes()};if(DF[5]==null){DF[5]=NowDate.getUTCSeconds()};if(DF[6]==null){DF[6]=NowDate.getUTCMilliseconds()};};if(DF[8]==null){return new Date(DF[0],DF[1],DF[2],DF[3],DF[4],DF[5],DF[6]);}else{if(DF[8]=="Z"||DF[8]=="UT"){return new Date(Date.UTC(DF[0],DF[1],DF[2],DF[3],DF[4],DF[5],DF[6]));}else{var ParsedTZ=new RegExp("^([\+\-])(1[012]|[0]?[0-9])(?::?)([0-5]?[0-9])$").exec(DF[8])
var CurTZ=new Date().getTimezoneOffset();var CurTZh=ParsedTZ[1]+ParsedTZ[2]-((CurTZ>=0?"-":"+")+Math.floor(Math.abs(CurTZ)/60))
var CurTZm=ParsedTZ[1]+ParsedTZ[3]-((CurTZ>=0?"-":"+")+(Math.abs(CurTZ)%60))
return new Date(DF[0],DF[1],DF[2],DF[3]-CurTZh,DF[4]-CurTZm,DF[5],DF[6]);};};return null;};Date.parseHttpTimeFormat=function(CurDate){if(typeof CurDate!="string"||CurDate==""){return null;};return Date.parseFormat(CurDate,"DDD, D MMM YYYY HH:mm:ss z");};Date.parseIso8601=function(CurDate){if(typeof CurDate!="string"||CurDate==""){return null;};var S="[\\-/:.]";var Yr="((?:1[6-9]|[2-9][0-9])[0-9]{2})";var Mo=S+"((?:1[012])|(?:0[1-9])|[1-9])";var Dy=S+"((?:3[01])|(?:[12][0-9])|(?:0[1-9])|[1-9])";var Hr="(2[0-4]|[01]?[0-9])";var Mn=S+"([0-5]?[0-9])";var Sd="(?:"+S+"([0-5]?[0-9])(?:[.,]([0-9]+))?)?";var TZ="(?:(Z)|(?:([\+\-])(1[012]|[0]?[0-9])(?::?([0-5]?[0-9]))?))?";var TF;if(TF=new RegExp("^"+Yr+"(?:"+Mo+"(?:"+Dy+")?)?"+"$").exec(CurDate)){}else if(TF=new RegExp("^"+Yr+Mo+Dy+"[Tt ]"+Hr+Mn+Sd+TZ+"$").exec(CurDate)){};if(!TF){return null};if(!TF[2]){TF[2]=1}else{TF[2]=TF[2]-1};if(!TF[3]){TF[3]=1};if(!TF[4]){TF[4]=0};if(!TF[5]){TF[5]=0};if(!TF[6]){TF[6]=0};if(!TF[7]){TF[7]=0};if(!TF[8]){TF[8]=null};if(TF[9]!="-"&&TF[9]!="+"){TF[9]=null};if(!TF[10]){TF[10]=0}else{TF[10]=TF[9]+TF[10]};if(!TF[11]){TF[11]=0}else{TF[11]=TF[9]+TF[11]};if(!TF[8]&&!TF[9]){return new Date(TF[1],TF[2],TF[3],TF[4],TF[5],TF[6],TF[7]);};if(TF[8]=="Z"){return new Date(Date.UTC(TF[1],TF[2],TF[3],TF[4],TF[5],TF[6],TF[7]));};if(TF[9]=="-"||TF[9]=="+"){var CurTZ=new Date().getTimezoneOffset();var CurTZh=TF[10]-((CurTZ>=0?"-":"+")+Math.floor(Math.abs(CurTZ)/60))
var CurTZm=TF[11]-((CurTZ>=0?"-":"+")+(Math.abs(CurTZ)%60))
return new Date(TF[1],TF[2],TF[3],TF[4]-CurTZh,TF[5]-CurTZm,TF[6],TF[7]);};return null;};Date.prototype.isWeekday=function(){if(this.getDay()!=0&&this.getDay()!=6){return true;}else{return false;};};Date.prototype.isLeapYear=function(){var CurYear=this.getFullYear();if(CurYear%400==0){return true;}else if(CurYear%100==0){return false;}else if(CurYear%4==0){return true;}else{return false;};};Date.prototype.dateFormat=function(Mask){var FormattedDate="";var MaskChars="DMY";var Ref_MonthFullName=["January","February","March","April","May","June","July","August","September","October","November","December"];var Ref_MonthAbbreviation=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];var Ref_DayFullName=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];var Ref_DayAbbreviation=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"];switch(Mask){case"short":Mask="M/D/YY";break;case"medium":Mask="MMM D, YYYY";break;case"long":Mask="MMMM D, YYYY";break;case"full":Mask="DDDD, MMMM D, YYYY";break;};Mask+=" ";var CurChar;var MaskPart="";for(var Cnt=0;Cnt<Mask.length;Cnt++){CurChar=Mask.charAt(Cnt);if((MaskChars.indexOf(CurChar)==-1)||(MaskPart!=""&&CurChar!=MaskPart.charAt(MaskPart.length-1))){if(MaskPart!=""){switch(MaskPart){case"D":FormattedDate+=this.getDate();break;case"DD":FormattedDate+=("0"+this.getDate()).slice(-2);break;case"DDD":FormattedDate+=Ref_DayAbbreviation[this.getDay()];break;case"DDDD":FormattedDate+=Ref_DayFullName[this.getDay()];break;case"M":FormattedDate+=this.getMonth()+1;break;case"MM":FormattedDate+=("0"+(this.getMonth()+1)).slice(-2);break;case"MMM":FormattedDate+=Ref_MonthAbbreviation[this.getMonth()];break;case"MMMM":FormattedDate+=Ref_MonthFullName[this.getMonth()];break;case"YY":FormattedDate+=("0"+this.getFullYear()).slice(-2);break;case"YYYY":FormattedDate+=("000"+this.getFullYear()).slice(-4);break;};MaskPart="";};if(MaskChars.indexOf(CurChar)>-1){MaskPart=CurChar;}else{FormattedDate+=CurChar;};}else{MaskPart+=CurChar;};};FormattedDate=FormattedDate.substring(0,FormattedDate.length-1);return FormattedDate;};Date.prototype.timeFormat=function(Mask){var FormattedTime="";var MaskChars="hHmsltT";switch(Mask){case"short":Mask="h:mm tt";break;case"medium":Mask="h:mm:ss tt";break;case"long":Mask="h:mm:ss.l tt";break;case"full":Mask="h:mm:ss.l tt";break;};Mask+=" ";var CurChar;var MaskPart="";for(var Cnt=0;Cnt<Mask.length;Cnt++){CurChar=Mask.charAt(Cnt);if((MaskChars.indexOf(CurChar)==-1)||(MaskPart!=""&&CurChar!=MaskPart.charAt(MaskPart.length-1))){if(MaskPart!=""){switch(MaskPart){case"h":var CurValue=this.getHours();if(CurValue>12){CurValue=CurValue-12;};FormattedTime+=CurValue;break;case"hh":var CurValue=this.getHours();if(CurValue>12){CurValue=CurValue-12;};FormattedTime+=("0"+CurValue).slice(-2);break;case"H":FormattedTime+=("0"+this.getHours()).slice(-2);break;case"HH":FormattedTime+=("0"+this.getHours()).slice(-2);break;case"m":FormattedTime+=this.getMinutes();break;case"mm":FormattedTime+=("0"+this.getMinutes()).slice(-2);break;case"s":FormattedTime+=this.getSeconds();break;case"ss":FormattedTime+=("0"+this.getSeconds()).slice(-2);break;case"l":FormattedTime+=("00"+this.getMilliseconds()).slice(-3);break;case"t":if(this.getHours()>12){FormattedTime+="p";}else{FormattedTime+="a";};break;case"tt":if(this.getHours()>12){FormattedTime+="pm";}else{FormattedTime+="am";};break;case"T":if(this.getHours()>12){FormattedTime+="P";}else{FormattedTime+="A";};break;case"TT":if(this.getHours()>12){FormattedTime+="PM";}else{FormattedTime+="AM";};break;};MaskPart="";};if(MaskChars.indexOf(CurChar)>-1){MaskPart=CurChar;}else{FormattedTime+=CurChar;};}else{MaskPart+=CurChar;};};FormattedTime=FormattedTime.substring(0,FormattedTime.length-1);return FormattedTime;};Date.prototype.iso8601Format=function(Style,isUTC){if(typeof Style!="string"&&typeof Style!="number"){var Style="YMDHMSM";};var FormattedDate="";var AddTZ=false;switch(Style){case"Y":case 1:FormattedDate+=this.dateFormat("YYYY");break;case"YM":case 2:FormattedDate+=this.dateFormat("YYYY-MM");break;case"YMD":case 3:FormattedDate+=this.dateFormat("YYYY-MM-DD");break;case"YMDHM":case 4:FormattedDate+=this.dateFormat("YYYY-MM-DD")+"T"+this.timeFormat("HH:mm");AddTZ=true;break;case"YMDHMS":case 5:FormattedDate+=this.dateFormat("YYYY-MM-DD")+"T"+this.timeFormat("HH:mm:ss");AddTZ=true;break;case"YMDHMSM":case 6:FormattedDate+=this.dateFormat("YYYY-MM-DD")+"T"+this.timeFormat("HH:mm:ss.l");AddTZ=true;break;};if(AddTZ){if(isUTC){FormattedDate+="Z";}else{var TimeZoneOffset=this.getTimezoneOffset();var TimeZoneInfo=(TimeZoneOffset>=0?"-":"+")+("0"+(Math.floor(Math.abs(TimeZoneOffset)/60))).slice(-2)+":"+("00"+(Math.abs(TimeZoneOffset)%60)).slice(-2);FormattedDate+=TimeZoneInfo;};};return FormattedDate;};Date.prototype.httpTimeFormat=function(isUTC){var FormattedDate="";FormattedDate+=this.dateFormat("DDD, D MMM YYYY ");FormattedDate+=this.timeFormat("HH:mm:ss ");if(isUTC){FormattedDate+="UT";}else{var TimeZoneOffset=this.getTimezoneOffset();var TimeZoneInfo=(TimeZoneOffset>=0?"-":"+")+("0"+(Math.floor(Math.abs(TimeZoneOffset)/60))).slice(-2)+("00"+(Math.abs(TimeZoneOffset)%60)).slice(-2);FormattedDate+=TimeZoneInfo;};return FormattedDate;};Date.prototype.dayOfYear=function(){var FirstOfYear=new Date(this.getFullYear(),0,1);return this.diff(FirstOfYear,"days")+1;};Date.prototype.weekOfYear=function(){var FirstOfYear=new Date(this.getFullYear(),0,1);return this.diff(FirstOfYear,"weeks")+1;};Date.prototype.add=function(Amount,DatePart,Destructive){DatePart=DatePart.toLowerCase();var ReturnDate=new Date(this);var CurAbsAmount=Math.abs(Amount);var Factors=new Object();Factors.milliseconds=1;Factors.seconds=1000;Factors.minutes=60000;Factors.quarterhours=900000;Factors.warhols=900000;Factors.halfhours=1800000;Factors.hours=3600000;Factors.days=86400000;Factors.weeks=604800000;switch(DatePart){case"milliseconds":case"seconds":case"minutes":case"quarterhours":case"warhols":case"halfhours":case"hours":case"days":case"weeks":ReturnDate=new Date(this.getTime()+(Amount*Factors[DatePart]));break;case"businessdays":if(CurAbsAmount>5){var CurWeeks=Math.floor(CurAbsAmount/5);var CurDays=CurAbsAmount%5;if(Amount<0){CurWeeks=-CurWeeks;CurDays=-CurDays;};}else{var CurWeeks=0;var CurDays=Amount;};ReturnDate=ReturnDate.add(CurWeeks,"weeks");ReturnDate=ReturnDate.add(CurDays,"days");if(ReturnDate.getDay()==0){if(Amount<0){ReturnDate=ReturnDate.add(-2,"days");}else{ReturnDate=ReturnDate.add(1,"days");};};if(ReturnDate.getDay()==6){if(Amount<0){ReturnDate=ReturnDate.add(-1,"days");}else{ReturnDate=ReturnDate.add(2,"days");};};break;case"businessweeks":ReturnDate=ReturnDate.add(Amount*5,"businessdays");break;case"wholeweeks":if(Amount<0){ReturnDate=ReturnDate.add(-(ReturnDate.getDay()),"days");}else{ReturnDate=ReturnDate.add(ReturnDate.getDay()+(6-ReturnDate.getDay()),"days");};ReturnDate=ReturnDate.add(Amount,"weeks");break;case"months":if(CurAbsAmount>11){var CurYears=Math.floor(CurAbsAmount/12);var CurMonths=CurAbsAmount%12;if(Amount<0){CurYears=-CurYears;CurMonths=-CurMonths;};}else{var CurYears=0;var CurMonths=Amount;};ReturnDate=ReturnDate.add(CurYears,"years");var TempReturnDate=new Date(ReturnDate);TempReturnDate.setDate(1);TempReturnDate=new Date(new Date(TempReturnDate).setMonth(TempReturnDate.getMonth()+CurMonths));ReturnDate=new Date(new Date(ReturnDate).setMonth(ReturnDate.getMonth()+CurMonths));if(ReturnDate.getMonth()!=TempReturnDate.getMonth()){ReturnDate.setDate(0)};break;case"years":var Feb29=false;if(ReturnDate.getMonth()==1&&ReturnDate.getDate()==29){Feb29=true;};ReturnDate=new Date(new Date(this).setFullYear(this.getFullYear()+Amount));if(Feb29){if(ReturnDate.getMonth!=1){ReturnDate.setDate(0);};};break;};if(!Destructive){return ReturnDate;}else{this.setTime(ReturnDate.getTime());return this;};};Date.prototype.diff=function(CompareDate,DatePart){DatePart=DatePart.toLowerCase();var Diff;if(this.getTime()<=CompareDate.getTime()){var Date1=new Date(this);var Date2=new Date(CompareDate);}else{var Date1=new Date(CompareDate);var Date2=new Date(this);};var Factors=new Object();Factors.milliseconds=1;Factors.seconds=1000;Factors.minutes=60000;Factors.quarterhours=900000;Factors.warhols=900000;Factors.halfhours=1800000;Factors.hours=3600000;Factors.days=86400000;Factors.weeks=604800000;switch(DatePart){case"milliseconds":case"seconds":case"minutes":case"quarterhours":case"warhols":case"halfhours":case"hours":case"days":case"weeks":var BaseDiff=Date1.getTime()-Date2.getTime();Diff=parseInt(BaseDiff/Factors[DatePart]);break;case"businessdays":var BDaysCnt=0;while(Date1.getTime()<Date2.getTime()){Date1=Date1.add(1,"days");if(Date1.getDay()>0&&Date1.getDay()<6){BDaysCnt++;};};if(Date2.getDay()==0||Date2.getDay()==6){Diff=BDaysCnt;}else{if(Date1.diff(Date2,"days")>0){Diff=BDaysCnt;}else{Diff=BDaysCnt-1;};};break;case"businessweeks":Diff=parseInt(Date1.diff(Date2,"businessdays")/5);break;case"wholeweeks":Date1=Date1.add(Date1.getDay()+(6-Date1.getDay()),"days");Diff=Date1.diff(Date2,"weeks");break;case"months":var MonthsCnt=Date1.diff(Date2,"years")*12;Date1=Date1.add(MonthsCnt,"months");while(Date1.getTime()<Date2.getTime()){Date1=Date1.add(1,"months");MonthsCnt++;};Diff=MonthsCnt-1;break;case"years":var YearsCnt=0;while(Date1.getTime()<Date2.getTime()){Date1=Date1.add(1,"years");YearsCnt++;};Diff=YearsCnt-1;break;};return Math.abs(Diff);};Date.prototype.compare=function(CompareDate,DatePart){if(!DatePart){var DatePart="millisecond";};DatePart=DatePart.toLowerCase();var Date1=new Date(this);var Date2=new Date(CompareDate);var Result;switch(DatePart){case"millisecond":break;case"second":Date1.setMilliseconds(1);Date2.setMilliseconds(1);break;case"minute":Date1.setMilliseconds(1);Date2.setMilliseconds(1);Date1.setSeconds(1);Date2.setSeconds(1);break;case"hour":Date1.setMilliseconds(1);Date2.setMilliseconds(1);Date1.setSeconds(1);Date2.setSeconds(1);Date1.setMinutes(1);Date2.setMinutes(1);break;case"day":Date1.setMilliseconds(1);Date2.setMilliseconds(1);Date1.setSeconds(1);Date2.setSeconds(1);Date1.setMinutes(1);Date2.setMinutes(1);Date1.setHours(1);Date2.setHours(1);break;case"month":Date1.setMilliseconds(1);Date2.setMilliseconds(1);Date1.setSeconds(1);Date2.setSeconds(1);Date1.setMinutes(1);Date2.setMinutes(1);Date1.setHours(1);Date2.setHours(1);Date1.setDate(1);Date2.setDate(1);break;case"year":Date1.setMilliseconds(1);Date2.setMilliseconds(1);Date1.setSeconds(1);Date2.setSeconds(1);Date1.setMinutes(1);Date2.setMinutes(1);Date1.setHours(1);Date2.setHours(1);Date1.setDate(1);Date2.setDate(1);Date1.setMonth(1);Date2.setMonth(1);break;};if(Date1.getTime()==Date2.getTime()){Result=0;}else if(Date1.getTime()<Date2.getTime()){Result=-1;}else{Result=1;};return Result;};



/* jQuery UI Date Picker v3.4 - previously jQuery Calendar

   Written by Marc Grabanski (m@marcgrabanski.com) and Keith Wood (kbwood@virginbroadband.com.au).



   Copyright (c) 2007 Marc Grabanski (http://marcgrabanski.com/code/ui-datepicker)

   Dual licensed under the MIT (MIT-LICENSE.txt)

   and GPL (GPL-LICENSE.txt) licenses.

   Date: 09-03-2007  */



/* Date picker manager.

   Use the singleton instance of this class, $.datepicker, to interact with the date picker.

   Settings for (groups of) date pickers are maintained in an instance object

   (DatepickerInstance), allowing multiple different settings on the same page. */

(function($){

    $.fn.validateHelper = function(el, options) {

        var main_options = $.extend({}, $.fn.inputUpdater.defaults, options);
        var options = $.meta ? $.extend({}, main_options, $this.data()) : main_options;
        return $.fn.validateHelper.validate(el, options);
   
    }

    $.fn.validateHelper.validate = function(el,options) { //decide which validations to use
            var t = options.rules.split(' ');
            var val = $(el).val();
            var canSubmit = true;
            for(i=0;i<t.length;i++)
            {
                    if(t[i] == 'required') canSubmit = $.fn.validateHelper.isRequired(val);
                    if(t[i] == 'state') canSubmit = $.fn.validateHelper.isState(val);
                    if(t[i] == 'alpha') canSubmit = $.fn.validateHelper.isAlpha(val);
                    if(t[i] == 'numeric') canSubmit = $.fn.validateHelper.isNumeric(val);
                    if(t[i] == 'email') canSubmit = $.fn.validateHelper.isEmail(val);
                    if(t[i] == 'postal') canSubmit = $.fn.validateHelper.isPostal(val);
                    if(t[i].match(/date/gi)!=null) canSubmit = $.fn.validateHelper.isDate(val);
                    if(t[i].match(/length/gi)!=null) canSubmit = $.fn.validateHelper.isLength(val, t[i]);
                    if(t[i].match(/creditcarddate/gi)!=null) canSubmit = $.fn.validateHelper.isCreditcarddate(val);
            }
        //    console.log(val+':'+canSubmit)
            return canSubmit;

        };

        $.fn.validateHelper.isRequired = function(val) { //make sure value is not empty
         //   console.log(val.length)
            if(val.length > 0) return true;
            else return false;
        };

        $.fn.validateHelper.isState = function(val) { //make sure value is not empty
         //   console.log(val.match(/\D{2}/))
            if(val.match(/[a-z]{2}/i)!=null) return true;
            else return false;
        };

        $.fn.validateHelper.isNumeric = function(val) { //make sure value is a digit
          //  console.log(val.match(/^\d*$/))
            if(val.match(/^\d*$/)!=null && val.match(/^\d*$/)!="") return true;
            else return false;
        };

        $.fn.validateHelper.isPostal = function(val) { //make sure value is a digit
            if(val.match(/^\d*$/)!=null && val.match(/^\d*$/)!="" && val.length == 5) return true;
            else return false;
        };

        $.fn.validateHelper.isAlpha = function(val) { //make sure value is a letter

            if(val.match(/\w/)!=null) return true;
            else return false;
        };

        $.fn.validateHelper.isAlphaNumeric = function(val) { //make sure value is a letter or number
             if(val.match(/\d\w/)!=null) return true;
             else return false;
        };

        $.fn.validateHelper.isEmail = function(val) { //make sure value is not empty
            if(val.match(/^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i)!=-1 && val.match(/^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i)!=null) return true;
            else return false;
        };

        $.fn.validateHelper.isDate = function(val) { //make sure value is a date
            //requires date.js
            val = ''+val;
            if(Date.parse(val) == null) return false;
            else return true;

        };


        $.fn.validateHelper.isCreditcarddate = function(val) { //make sure value is a valid date for creditcard - date must be > today
            //requires date.js
            var today = Date.today().set({day:1});
            var future = Date.parse(''+val);
            if(Date.today().set({day:1}).compareTo(future) < 1) return true;
            else return false;

        };

        $.fn.validateHelper.isLength = function(val,len) { //make sure value is a digit
            var s = len.split('_');
            if(val.length == s[1]) return true;
            else return false;
        };

        $.fn.validateHelper.doValidation = function(el)
        {
            $(el).parents('li').find('div.omnierror').remove();
             var valid = true;


             if($(el).attr('req')!=undefined && $(el).attr('req')!='') valid = $.fn.validateHelper(el,{rules:$(el).attr('req')});
             return valid;
        }


        $.fn.validateHelper.omnitipError = function(el)
        {
           
            var err = $(el).attr('err');
                      $(el).parents('li').append('<div class="omnierror" err="'+err+'">x</div>')
                       makeErrorOmnitip($(el).parents('li').find('div.omnierror'), 'err');  //bj.global
                      $(el).removeClass('vh_valid').addClass('vh_invalid');
        }

        $.fn.validateHelper.omnitipSuccess = function(el)
        {
            $(el).removeClass('vh_invalid').addClass('vh_valid');
        }
   
})(jQuery);


(function($) {



        $.fn.inputUpdater = function(options) {
        
        var main_options = $.extend({}, $.fn.inputUpdater.defaults, options);

        //clear errors
        $(".iu_validate_error").remove();

            return this.each(function() {
                $this = $(this);
                 // if metadata is present, extend main_opts, otherwise just use main_opts
                var options = $.meta ? $.extend({}, main_options, $this.data()) : main_options;


                if($this.attr('type')=='text')
                {
                     $this.unbind().focus(function(){$.fn.inputUpdater.focus(this,options);return false;});
                     $this.unbind().keyup(function(){$.fn.inputUpdater.keyup(this,options);return false;});
                     $this.bind('keydown', 'return', function(){return false;});
                }
                else if ($this.attr('class').match(/save/i))
                {
                     $this.unbind().click(function(){$.fn.inputUpdater.update(this,options);return false;});
                }
                else if ($this.attr('class')=='load')
                {
                    $.fn.inputUpdater.update(this,options);
                }
                else if ($this.attr('class').match(/insert/) !=null)
                {
                     $this.unbind().click(function(){$.fn.inputUpdater.full(this,options);return false;});
                }
                else if($this.attr('type') =='radio')
                {
                     $this.unbind().click(function(){$.fn.inputUpdater.radio(this,options);return true;});
                }
                else
                {
                 
                     $this.unbind().change(function(){$.fn.inputUpdater.keyup(this,options);return false;});
                }
            });
        };

        $.fn.inputUpdater.focus = function(el,options) {  //on focus
           var $this = $(el);
        };

        $.fn.inputUpdater.keyup = function(el,options) { //if length is > 0 and check option setting for validation
                   $.fn.inputUpdater.clearTimer(el,options);
                   $.fn.inputUpdater.setTimer(el,options);
        };

        $.fn.inputUpdater.radio = function(el,options) { //if length is > 0 and check option setting for validation
                var $this = $(el);
                $this.attr('checked','checked');
                $.fn.inputUpdater.update($this,options);

        };

        $.fn.inputUpdater.validate = function(val, type) { //decide which validations to use
            var t = type.split(' ');
            var canSubmit = true;
            for(i=0;i<t.length;i++)
            {
                    if(t[i] == 'required') canSubmit = $.fn.inputUpdater.isRequired(val);
                    if(t[i] == 'alpha') canSubmit = $.fn.inputUpdater.isAlpha(val);
                    if(t[i] == 'numeric') canSubmit = $.fn.inputUpdater.isNumeric(val);
                    if(t[i].match(/date/gi)!=null) canSubmit = $.fn.inputUpdater.isDate(val);
                    if(t[i].match(/length/gi)!=null) canSubmit = $.fn.inputUpdater.isLength(val, t[i]);
                    if(t[i].match(/creditcarddate/gi)!=null) canSubmit = $.fn.inputUpdater.isCreditcarddate(val);
            }
        //    console.log(val+':'+canSubmit)
            return canSubmit;

        };

        $.fn.inputUpdater.isRequired = function(val) { //make sure value is not empty
         //   console.log(val.length)
            if(val.length > 0) return true;
            else return false;
        };

        $.fn.inputUpdater.isNumeric = function(val) { //make sure value is a digit
          //  console.log(val.match(/^\d*$/))
            if(val.match(/^\d*$/)!=null && val.match(/^\d*$/)!="") return true;
            else return false;
        };

        $.fn.inputUpdater.isAlpha = function(val) { //make sure value is a letter

            if(val.match(/\w/)!=null) return true;
            else return false;
        };

        $.fn.inputUpdater.isAlphaNumeric = function(val) { //make sure value is a letter or number
             if(val.match(/\d\w/)!=null) return true;
             else return false;
        };

        $.fn.inputUpdater.isDate = function(val) { //make sure value is a date
            //requires date.js
            val = ''+val;
            if(Date.parse(val) == null) return false;
            else return true;

        };


        $.fn.inputUpdater.isCreditcarddate = function(val) { //make sure value is a valid date for creditcard - date must be > today
            //requires date.js
            var today = Date.today().set({day:1});
            var future = Date.parse(''+val);
            if(Date.today().set({day:1}).compareTo(future) < 1) return true;
            else return false;

        };

        $.fn.inputUpdater.isLength = function(val,len) { //make sure value is a digit
            var s = len.split('_');
            if(val.length == s[1]) return true;
            else return false;
        };

        $.fn.inputUpdater.error = function(el,options){
            var $this = $(el);
            var id = $this.attr('id');
       
            $("body").append('<div id="error_'+id+'" class="iu_validate_error fg-tooltip ui-widget ui-widget-content ui-corner-all">'+options.errorMessage+'<div class="fg-tooltip-pointer-down ui-widget-content"><div class="fg-tooltip-pointer-down-inner"></div></div></div>')

            $("#error_"+id).alignElements(el,{alignHorizontal:'top',alignVertical:'center',modifyHorizontal:-5});
            if($this.siblings('div.loading').html()!=null) $this.siblings('div.loading').remove();

/*
            $(".iu_validate_error").tooltip({
                track: true,
                delay: 0,
                showURL: false,
                opacity: 1,
                fixPNG: true,
                showBody: " - ",
                extraClass: "dialog",
                top: -15,
                left: 0
            });
            */
        };

         $.fn.inputUpdater.update = function(el,options){
            var $this = $(el);
            var form = {};
            var name = $this.attr('name');
            var value = $this.attr('value');

            if(value==null)
            {
                //see if there is a form field behind it
                value=$this.prev().val();
                name=$this.prev().attr('name');
            }
            
            
            var parent = $.fn.inputUpdater.getParent(el,options);
            parent.children('div').children('div.iu_validate_error').remove();
          //  debug(parent)
            var id = parent.attr('id');
            var id_split= id.split('_');
            form['id'] = id_split[1];
            form[name] = value;
            form['action'] = options.actionType;

            //convert date entries
            if(options.valueType.match(/creditcarddate/gi))
                {
                    var date = Date.parse(''+value);
                    if(date!=null) value = date.toString('MM / yyyy');
                    form[name] = value;
                    if($this.prev().attr('type')=='text') $this.prev().val(''+value);
                }

            var canSubmit = true;
            if($.isFunction(options.presubmitCallback)) canSubmit = options.presubmitCallback(el,parent,options);
            
            if(options.valueType!='')
                {
                   
                    canSubmit = $.fn.inputUpdater.validate(value,options.valueType);
                }
            if(canSubmit) $.fn.inputUpdater.submit(el,options,form);
            else $.fn.inputUpdater.error($this,options);
        };

        $.fn.inputUpdater.getName = function(el)
        {
            var field = $(el).attr('name');
            var field_split = field.split('_');
            return field_split[0];
        }


        $.fn.inputUpdater.full = function(el,options){
            var $this = $(el);
            var form = {};
            
            var parent = $.fn.inputUpdater.getParent(el,options);
            var pID = parent.attr('id');
            var canSubmit = true;
            var e = 0;

           $('#'+pID+' input').each(function(){
                var field = $.fn.inputUpdater.getName(this);

                

                if($(this).attr('type') == 'radio')
                {
                    if($(this).is(':checked')) form[field] = $(this).val();
                }
                else
                {
                     form[field] = $(this).val();
                }


                if($(this).attr('rel'))
                {
                    var type= $(this).attr('rel');
                    options.errorMessage = $(this).attr('msg');
                  //  console.log(options.errorMessage)
                    if(options.errorMessage == '' || options.errorMessage=='undefined') options.errorMessage = 'This field is required';

                    canSubmit= $.fn.inputUpdater.validate(form[field],type);
                    if(!canSubmit)
                        {
                            $.fn.inputUpdater.error($(this),options);
                            e++;
                        }
                }

            });

            $('#'+pID+' select').each(function(){
               var field = $.fn.inputUpdater.getName(this);
               form[field] = $(this).val();

                if($(this).attr('rel'))
                {
                    var type= $(this).attr('rel');

                    var canSubmit= $.fn.inputUpdater.validate(form[field],type);
                    if(!canSubmit)
                        {
                            $.fn.inputUpdater.error($(this),options);
                            e++;
                        }
                }

            });

            form['action'] = options.actionType;
            if(options.actionType!='insert')
                {
                    var sid = pID.split('_');
                    form['id'] = sid[1];
                }

            if($.isFunction(options.presubmitCallback)) canSubmit = options.presubmitCallback(el,parent,options);

            if(e==0 && canSubmit) $.fn.inputUpdater.submit(el,options,form);
        };

        


        $.fn.inputUpdater.submit = function(el,options,form)
        {
            $.ajax({
                url: options.submitPath,
                data:form,
                dataType: options.dataType,
				success: function (data, textStatus) {
                    $.fn.inputUpdater.responseSuccess(el,options,data)
                },
				error: function(XMLHttpRequest, textStatus, errorThrown){
                    $.fn.inputUpdater.responseError(el,options)
                },
				beforeSend: function (XMLHttpRequest) {
                    $.fn.inputUpdater.ajaxLoading(el,options)
                },
				complete: function (XMLHttpRequest) {
                    $.fn.inputUpdater.ajaxComplete(el,options)
                }
			});
        }


        $.fn.inputUpdater.getParent = function(el,options)
        {
            var $this=$(el);
            if(options.parent!='')
                {
                    //another hack :)
                    var theparent = $this.parents(options.parent);
                    if($this.parent().attr('class').match(/saveBTN/g)!='' && $this.parent().attr('class').match(/saveBTN/g)!=null)
                    {
                       theparent = $this.parent().next();
                    }

                    return theparent;
                }
            else return $this;
        }

        $.fn.inputUpdater.responseSuccess = function(el,options,data)
        {
            var $this = $(el);
            var parent = $.fn.inputUpdater.getParent(el,options);

            if(data.success==false)
            {
                $.fn.inputUpdater.jsonFail(el,options,data);

            }
            else
            {
            
            if(options.parent =='tr') parent.children('td').effect("highlight",{},2000);
            else  parent.effect("highlight",{},2000);
           

          //  $this.after('<div class="response_success"><img src="'+options.successImagePath+'"  /></div>');
            if($this.attr('name') == 'quantity' && $this.val()==0) $this.attr('name','delete');
            $this.siblings('div.loading').html('<img src="'+options.successImagePath+'"  />').oneTime(1000, function() {
                $(this).fadeOut(200,function(){
                    $(this).remove();
                    if($this.attr('name') == 'delete')
                    {
                        $this.parents(options.parent).fadeOut(500,function(){$(this).remove()});
                    }
                     if($.isFunction(options.submitCallback)) options.submitCallback(el,parent,options, data);
                });
            });

            }

        }

        $.fn.inputUpdater.jsonFail = function(el,options,data)
        {
            if(data.error == "Address not found")
                {
                     $this.siblings('div.loading').html('<img class="error_btn" title="there has been an error updating the database. please try again" src="'+options.errorImagePath+'"  />')
                    var html = '<li class="address_not_found" style="width:100%"><div class="alert"><input style="width:20px;background:none;border:0;" type="checkbox" name="overrideAddress" id="f_overrideAddressFailure" value="true" /> This address was not found in the USPS database. Please check this box and resubmit if you would like to use this address.</div></li>';
                    var parent = $.fn.inputUpdater.getParent(el,options);
                    if(parent.children('li').children('div.alert').length == 0) {
                        parent.prepend(html);
                        if($(".saveBTN").length > 0)
                        {
                         $(".saveBTN").alignElements(parent,{alignVertical:'right',modifyHorizontal:20,modifyVertical:-20});
                        }
                    }
                }
            else
                {
                    options.errorMessage = data.error;
                     $.fn.inputUpdater.error(el,options);
                }
        }

        $.fn.inputUpdater.responseError = function(el,options)
        {
            var $this = $(el);
            var parent = $.fn.inputUpdater.getParent(el,options);
            if(options.parent =='tr') parent.children('td').effect("highlight",{color:'#f4760f'},2000);
            else  parent.effect("highlight",{color:'#f4760f'},2000);

           // $this.after('<div class="response_error" title="there has been an error updating the database. please try again"><img src="'+options.errorImagePath+'"  /></div>');


            $this.siblings('div.loading').html('<img class="error_btn" title="there has been an error updating the database. please try again" src="'+options.errorImagePath+'"  />').oneTime(1000, function() {
                $(this).fadeOut(500,function(){$(this).remove()});
            });

        }

        $.fn.inputUpdater.ajaxLoading = function(el,options)
        {
            $(".iu_validate_error").remove();
            var $this = $(el);
            $this.after('<div class="loading"></div>');
           // $this.next().alignElements(el,{alignVertical:'right',alignHorizontal:'center',modifyVertical:5,modifyHorizontal:3});
           ajaxicator($this);
        }

        $.fn.inputUpdater.ajaxComplete = function(el,options)
        {
            var $this = $(el);
            ajaxicator($this,'off');
         //   if($this.siblings('div.loading').html()!=null) $this.siblings('div.loading').remove();
        }

        $.fn.inputUpdater.defaults = {
            valueType: '', //possible values = numeric, alpha, alphanumeric. any
            ajaxSubmit:'true', //submit the changes - for real-time updates, otherwise can use this for validation
            dataType: 'json', //how form submit data is returned - same params as jquery ajax object http://docs.jquery.com/Ajax/jQuery.ajax#options
            errorMessage: 'this field is required',
            actionType: 'update', //action taken by SQL
            submitSuccessMessage: null, //message for users when form submission succeeds
  			submitCallback: null, //callback function for submit
            presubmitCallback: null, //callback function for use before the submit - good for specialty validation
  			loadingImagePath: 'images/ajax-loader.gif', //location of loading animated gif
            errorImagePath: 'images/indicator_error.gif', //location of loading animated gif
            successImagePath: 'images/indicator_success.gif', //location of loading animated gif
            parent: ''
        };


       $.fn.inputUpdater.setTimer = function(el,options) {
			     	$(el).oneTime(500,"timer_",function () {

                        var $this = $(el);
                        var value = $this.val();
                        if(value.length > 0)
                        {

                         if($this.next().attr('class','iu_validate_error')) $this.next().remove();
                         var valid = $.fn.inputUpdater.validate(value,options.valueType);
                         if(valid) $.fn.inputUpdater.update($this,options);
                         else $.fn.inputUpdater.error($this,options);
                       }

			      	});

				}

		$.fn.inputUpdater.clearTimer = function(el){
					$(el).stopTime('timer_');
				}


        function debug($obj) {
          if (window.console && window.console.log)
            window.console.log($obj);
        };

    })(jQuery);

	
function runLabelOver()
    {
        $(".label_over label").each(function(){
             if($(this).parents('li').children('input').val()!='' && $(this).parents('li').children('input').val()!=null && $(this).parents('li').children('input').val()!=undefined) $(this).hide();
             if($(this).parents('li').children('textarea').val()!='' && $(this).parents('li').children('textarea').val()!=null && $(this).parents('li').children('textarea').val()!=undefined) $(this).hide();
        })

         $(".label_over label").unbind().click(function(){
           runOver(this);
        });

        $(".label_over input").unbind().focus(function(){
           runOver(this);
        })

        $(".label_over textarea").unbind().focus(function(){
           runOver(this);
        })

        $(".label_over input").click(function(){
           runOver(this);
        })

         $(".label_over textarea").click(function(){
           runOver(this);
        })

        $(".label_over input").blur(function(){
           runOut(this);
        });

         $(".label_over textarea").blur(function(){
           runOut(this);
        });

    }

    function runOver(el)
    {
        var label =  $(el).parents('li').children('label');
        if(label.is(':visible'))
            {
                label.hide();
                 $(el).parents('li').children('input').focus();
                 $(el).parents('li').children('textarea').focus();
            }

    }

    function runOut(el)
    {
        var label =  $(el).parents('li').children('label');
        if($(el).parents('li').children('input').val() == '')
            {
                 label.show();
            }
       else if($(el).parents('li').children('textarea').val() == '')
            {
                 label.show();
            }
    }
