/**
 * Version: 1.0 Alpha-1
 * Build Date: 13-Nov-2007
 * Copyright (c) 2006-2007, Coolite Inc. (http://www.coolite.com/). All rights reserved.
 * License: Licensed under The MIT License. See license.txt and http://www.datejs.com/license/.
 * Website: http://www.datejs.com/ or http://www.coolite.com/datejs/
 */
Date.CultureInfo={name:"en-US",englishName:"English (United States)",nativeName:"English (United States)",dayNames:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],abbreviatedDayNames:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],shortestDayNames:["Su","Mo","Tu","We","Th","Fr","Sa"],firstLetterDayNames:["S","M","T","W","T","F","S"],monthNames:["January","February","March","April","May","June","July","August","September","October","November","December"],abbreviatedMonthNames:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],amDesignator:"AM",pmDesignator:"PM",firstDayOfWeek:0,twoDigitYearMax:2029,dateElementOrder:"mdy",formatPatterns:{shortDate:"M/d/yyyy",longDate:"dddd, MMMM dd, yyyy",shortTime:"h:mm tt",longTime:"h:mm:ss tt",fullDateTime:"dddd, MMMM dd, yyyy h:mm:ss tt",sortableDateTime:"yyyy-MM-ddTHH:mm:ss",universalSortableDateTime:"yyyy-MM-dd HH:mm:ssZ",rfc1123:"ddd, dd MMM yyyy HH:mm:ss GMT",monthDay:"MMMM dd",yearMonth:"MMMM, yyyy"},regexPatterns:{jan:/^jan(uary)?/i,feb:/^feb(ruary)?/i,mar:/^mar(ch)?/i,apr:/^apr(il)?/i,may:/^may/i,jun:/^jun(e)?/i,jul:/^jul(y)?/i,aug:/^aug(ust)?/i,sep:/^sep(t(ember)?)?/i,oct:/^oct(ober)?/i,nov:/^nov(ember)?/i,dec:/^dec(ember)?/i,sun:/^su(n(day)?)?/i,mon:/^mo(n(day)?)?/i,tue:/^tu(e(s(day)?)?)?/i,wed:/^we(d(nesday)?)?/i,thu:/^th(u(r(s(day)?)?)?)?/i,fri:/^fr(i(day)?)?/i,sat:/^sa(t(urday)?)?/i,future:/^next/i,past:/^last|past|prev(ious)?/i,add:/^(\+|after|from)/i,subtract:/^(\-|before|ago)/i,yesterday:/^yesterday/i,today:/^t(oday)?/i,tomorrow:/^tomorrow/i,now:/^n(ow)?/i,millisecond:/^ms|milli(second)?s?/i,second:/^sec(ond)?s?/i,minute:/^min(ute)?s?/i,hour:/^h(ou)?rs?/i,week:/^w(ee)?k/i,month:/^m(o(nth)?s?)?/i,day:/^d(ays?)?/i,year:/^y((ea)?rs?)?/i,shortMeridian:/^(a|p)/i,longMeridian:/^(a\.?m?\.?|p\.?m?\.?)/i,timezone:/^((e(s|d)t|c(s|d)t|m(s|d)t|p(s|d)t)|((gmt)?\s*(\+|\-)\s*\d\d\d\d?)|gmt)/i,ordinalSuffix:/^\s*(st|nd|rd|th)/i,timeContext:/^\s*(\:|a|p)/i},abbreviatedTimeZoneStandard:{GMT:"-000",EST:"-0400",CST:"-0500",MST:"-0600",PST:"-0700"},abbreviatedTimeZoneDST:{GMT:"-000",EDT:"-0500",CDT:"-0600",MDT:"-0700",PDT:"-0800"}};
Date.getMonthNumberFromName=function(name){var n=Date.CultureInfo.monthNames,m=Date.CultureInfo.abbreviatedMonthNames,s=name.toLowerCase();for(var i=0;i<n.length;i++){if(n[i].toLowerCase()==s||m[i].toLowerCase()==s){return i;}}
return-1;};Date.getDayNumberFromName=function(name){var n=Date.CultureInfo.dayNames,m=Date.CultureInfo.abbreviatedDayNames,o=Date.CultureInfo.shortestDayNames,s=name.toLowerCase();for(var i=0;i<n.length;i++){if(n[i].toLowerCase()==s||m[i].toLowerCase()==s){return i;}}
return-1;};Date.isLeapYear=function(year){return(((year%4===0)&&(year%100!==0))||(year%400===0));};Date.getDaysInMonth=function(year,month){return[31,(Date.isLeapYear(year)?29:28),31,30,31,30,31,31,30,31,30,31][month];};Date.getTimezoneOffset=function(s,dst){return(dst||false)?Date.CultureInfo.abbreviatedTimeZoneDST[s.toUpperCase()]:Date.CultureInfo.abbreviatedTimeZoneStandard[s.toUpperCase()];};Date.getTimezoneAbbreviation=function(offset,dst){var n=(dst||false)?Date.CultureInfo.abbreviatedTimeZoneDST:Date.CultureInfo.abbreviatedTimeZoneStandard,p;for(p in n){if(n[p]===offset){return p;}}
return null;};Date.prototype.clone=function(){return new Date(this.getTime());};Date.prototype.compareTo=function(date){if(isNaN(this)){throw new Error(this);}
if(date instanceof Date&&!isNaN(date)){return(this>date)?1:(this<date)?-1:0;}else{throw new TypeError(date);}};Date.prototype.equals=function(date){return(this.compareTo(date)===0);};Date.prototype.between=function(start,end){var t=this.getTime();return t>=start.getTime()&&t<=end.getTime();};Date.prototype.addMilliseconds=function(value){this.setMilliseconds(this.getMilliseconds()+value);return this;};Date.prototype.addSeconds=function(value){return this.addMilliseconds(value*1000);};Date.prototype.addMinutes=function(value){return this.addMilliseconds(value*60000);};Date.prototype.addHours=function(value){return this.addMilliseconds(value*3600000);};Date.prototype.addDays=function(value){return this.addMilliseconds(value*86400000);};Date.prototype.addWeeks=function(value){return this.addMilliseconds(value*604800000);};Date.prototype.addMonths=function(value){var n=this.getDate();this.setDate(1);this.setMonth(this.getMonth()+value);this.setDate(Math.min(n,this.getDaysInMonth()));return this;};Date.prototype.addYears=function(value){return this.addMonths(value*12);};Date.prototype.add=function(config){if(typeof config=="number"){this._orient=config;return this;}
var x=config;if(x.millisecond||x.milliseconds){this.addMilliseconds(x.millisecond||x.milliseconds);}
if(x.second||x.seconds){this.addSeconds(x.second||x.seconds);}
if(x.minute||x.minutes){this.addMinutes(x.minute||x.minutes);}
if(x.hour||x.hours){this.addHours(x.hour||x.hours);}
if(x.month||x.months){this.addMonths(x.month||x.months);}
if(x.year||x.years){this.addYears(x.year||x.years);}
if(x.day||x.days){this.addDays(x.day||x.days);}
return this;};Date._validate=function(value,min,max,name){if(typeof value!="number"){throw new TypeError(value+" is not a Number.");}else if(value<min||value>max){throw new RangeError(value+" is not a valid value for "+name+".");}
return true;};Date.validateMillisecond=function(n){return Date._validate(n,0,999,"milliseconds");};Date.validateSecond=function(n){return Date._validate(n,0,59,"seconds");};Date.validateMinute=function(n){return Date._validate(n,0,59,"minutes");};Date.validateHour=function(n){return Date._validate(n,0,23,"hours");};Date.validateDay=function(n,year,month){return Date._validate(n,1,Date.getDaysInMonth(year,month),"days");};Date.validateMonth=function(n){return Date._validate(n,0,11,"months");};Date.validateYear=function(n){return Date._validate(n,1,9999,"seconds");};Date.prototype.set=function(config){var x=config;if(!x.millisecond&&x.millisecond!==0){x.millisecond=-1;}
if(!x.second&&x.second!==0){x.second=-1;}
if(!x.minute&&x.minute!==0){x.minute=-1;}
if(!x.hour&&x.hour!==0){x.hour=-1;}
if(!x.day&&x.day!==0){x.day=-1;}
if(!x.month&&x.month!==0){x.month=-1;}
if(!x.year&&x.year!==0){x.year=-1;}
if(x.millisecond!=-1&&Date.validateMillisecond(x.millisecond)){this.addMilliseconds(x.millisecond-this.getMilliseconds());}
if(x.second!=-1&&Date.validateSecond(x.second)){this.addSeconds(x.second-this.getSeconds());}
if(x.minute!=-1&&Date.validateMinute(x.minute)){this.addMinutes(x.minute-this.getMinutes());}
if(x.hour!=-1&&Date.validateHour(x.hour)){this.addHours(x.hour-this.getHours());}
if(x.month!==-1&&Date.validateMonth(x.month)){this.addMonths(x.month-this.getMonth());}
if(x.year!=-1&&Date.validateYear(x.year)){this.addYears(x.year-this.getFullYear());}
if(x.day!=-1&&Date.validateDay(x.day,this.getFullYear(),this.getMonth())){this.addDays(x.day-this.getDate());}
if(x.timezone){this.setTimezone(x.timezone);}
if(x.timezoneOffset){this.setTimezoneOffset(x.timezoneOffset);}
return this;};Date.prototype.clearTime=function(){this.setHours(0);this.setMinutes(0);this.setSeconds(0);this.setMilliseconds(0);return this;};Date.prototype.isLeapYear=function(){var y=this.getFullYear();return(((y%4===0)&&(y%100!==0))||(y%400===0));};Date.prototype.isWeekday=function(){return!(this.is().sat()||this.is().sun());};Date.prototype.getDaysInMonth=function(){return Date.getDaysInMonth(this.getFullYear(),this.getMonth());};Date.prototype.moveToFirstDayOfMonth=function(){return this.set({day:1});};Date.prototype.moveToLastDayOfMonth=function(){return this.set({day:this.getDaysInMonth()});};Date.prototype.moveToDayOfWeek=function(day,orient){var diff=(day-this.getDay()+7*(orient||+1))%7;return this.addDays((diff===0)?diff+=7*(orient||+1):diff);};Date.prototype.moveToMonth=function(month,orient){var diff=(month-this.getMonth()+12*(orient||+1))%12;return this.addMonths((diff===0)?diff+=12*(orient||+1):diff);};Date.prototype.getDayOfYear=function(){return Math.floor((this-new Date(this.getFullYear(),0,1))/86400000);};Date.prototype.getWeekOfYear=function(firstDayOfWeek){var y=this.getFullYear(),m=this.getMonth(),d=this.getDate();var dow=firstDayOfWeek||Date.CultureInfo.firstDayOfWeek;var offset=7+1-new Date(y,0,1).getDay();if(offset==8){offset=1;}
var daynum=((Date.UTC(y,m,d,0,0,0)-Date.UTC(y,0,1,0,0,0))/86400000)+1;var w=Math.floor((daynum-offset+7)/7);if(w===dow){y--;var prevOffset=7+1-new Date(y,0,1).getDay();if(prevOffset==2||prevOffset==8){w=53;}else{w=52;}}
return w;};Date.prototype.isDST=function(){console.log('isDST');return this.toString().match(/(E|C|M|P)(S|D)T/)[2]=="D";};Date.prototype.getTimezone=function(){return Date.getTimezoneAbbreviation(this.getUTCOffset,this.isDST());};Date.prototype.setTimezoneOffset=function(s){var here=this.getTimezoneOffset(),there=Number(s)*-6/10;this.addMinutes(there-here);return this;};Date.prototype.setTimezone=function(s){return this.setTimezoneOffset(Date.getTimezoneOffset(s));};Date.prototype.getUTCOffset=function(){var n=this.getTimezoneOffset()*-10/6,r;if(n<0){r=(n-10000).toString();return r[0]+r.substr(2);}else{r=(n+10000).toString();return"+"+r.substr(1);}};Date.prototype.getDayName=function(abbrev){return abbrev?Date.CultureInfo.abbreviatedDayNames[this.getDay()]:Date.CultureInfo.dayNames[this.getDay()];};Date.prototype.getMonthName=function(abbrev){return abbrev?Date.CultureInfo.abbreviatedMonthNames[this.getMonth()]:Date.CultureInfo.monthNames[this.getMonth()];};Date.prototype._toString=Date.prototype.toString;Date.prototype.toString=function(format){var self=this;var p=function p(s){return(s.toString().length==1)?"0"+s:s;};return format?format.replace(/dd?d?d?|MM?M?M?|yy?y?y?|hh?|HH?|mm?|ss?|tt?|zz?z?/g,function(format){switch(format){case"hh":return p(self.getHours()<13?self.getHours():(self.getHours()-12));case"h":return self.getHours()<13?self.getHours():(self.getHours()-12);case"HH":return p(self.getHours());case"H":return self.getHours();case"mm":return p(self.getMinutes());case"m":return self.getMinutes();case"ss":return p(self.getSeconds());case"s":return self.getSeconds();case"yyyy":return self.getFullYear();case"yy":return self.getFullYear().toString().substring(2,4);case"dddd":return self.getDayName();case"ddd":return self.getDayName(true);case"dd":return p(self.getDate());case"d":return self.getDate().toString();case"MMMM":return self.getMonthName();case"MMM":return self.getMonthName(true);case"MM":return p((self.getMonth()+1));case"M":return self.getMonth()+1;case"t":return self.getHours()<12?Date.CultureInfo.amDesignator.substring(0,1):Date.CultureInfo.pmDesignator.substring(0,1);case"tt":return self.getHours()<12?Date.CultureInfo.amDesignator:Date.CultureInfo.pmDesignator;case"zzz":case"zz":case"z":return"";}}):this._toString();};
Date.now=function(){return new Date();};Date.today=function(){return Date.now().clearTime();};Date.prototype._orient=+1;Date.prototype.next=function(){this._orient=+1;return this;};Date.prototype.last=Date.prototype.prev=Date.prototype.previous=function(){this._orient=-1;return this;};Date.prototype._is=false;Date.prototype.is=function(){this._is=true;return this;};Number.prototype._dateElement="day";Number.prototype.fromNow=function(){var c={};c[this._dateElement]=this;return Date.now().add(c);};Number.prototype.ago=function(){var c={};c[this._dateElement]=this*-1;return Date.now().add(c);};(function(){var $D=Date.prototype,$N=Number.prototype;var dx=("sunday monday tuesday wednesday thursday friday saturday").split(/\s/),mx=("january february march april may june july august september october november december").split(/\s/),px=("Millisecond Second Minute Hour Day Week Month Year").split(/\s/),de;var df=function(n){return function(){if(this._is){this._is=false;return this.getDay()==n;}
return this.moveToDayOfWeek(n,this._orient);};};for(var i=0;i<dx.length;i++){$D[dx[i]]=$D[dx[i].substring(0,3)]=df(i);}
var mf=function(n){return function(){if(this._is){this._is=false;return this.getMonth()===n;}
return this.moveToMonth(n,this._orient);};};for(var j=0;j<mx.length;j++){$D[mx[j]]=$D[mx[j].substring(0,3)]=mf(j);}
var ef=function(j){return function(){if(j.substring(j.length-1)!="s"){j+="s";}
return this["add"+j](this._orient);};};var nf=function(n){return function(){this._dateElement=n;return this;};};for(var k=0;k<px.length;k++){de=px[k].toLowerCase();$D[de]=$D[de+"s"]=ef(px[k]);$N[de]=$N[de+"s"]=nf(de);}}());Date.prototype.toJSONString=function(){return this.toString("yyyy-MM-ddThh:mm:ssZ");};Date.prototype.toShortDateString=function(){return this.toString(Date.CultureInfo.formatPatterns.shortDatePattern);};Date.prototype.toLongDateString=function(){return this.toString(Date.CultureInfo.formatPatterns.longDatePattern);};Date.prototype.toShortTimeString=function(){return this.toString(Date.CultureInfo.formatPatterns.shortTimePattern);};Date.prototype.toLongTimeString=function(){return this.toString(Date.CultureInfo.formatPatterns.longTimePattern);};Date.prototype.getOrdinal=function(){switch(this.getDate()){case 1:case 21:case 31:return"st";case 2:case 22:return"nd";case 3:case 23:return"rd";default:return"th";}};
(function(){Date.Parsing={Exception:function(s){this.message="Parse error at '"+s.substring(0,10)+" ...'";}};var $P=Date.Parsing;var _=$P.Operators={rtoken:function(r){return function(s){var mx=s.match(r);if(mx){return([mx[0],s.substring(mx[0].length)]);}else{throw new $P.Exception(s);}};},token:function(s){return function(s){return _.rtoken(new RegExp("^\s*"+s+"\s*"))(s);};},stoken:function(s){return _.rtoken(new RegExp("^"+s));},until:function(p){return function(s){var qx=[],rx=null;while(s.length){try{rx=p.call(this,s);}catch(e){qx.push(rx[0]);s=rx[1];continue;}
break;}
return[qx,s];};},many:function(p){return function(s){var rx=[],r=null;while(s.length){try{r=p.call(this,s);}catch(e){return[rx,s];}
rx.push(r[0]);s=r[1];}
return[rx,s];};},optional:function(p){return function(s){var r=null;try{r=p.call(this,s);}catch(e){return[null,s];}
return[r[0],r[1]];};},not:function(p){return function(s){try{p.call(this,s);}catch(e){return[null,s];}
throw new $P.Exception(s);};},ignore:function(p){return p?function(s){var r=null;r=p.call(this,s);return[null,r[1]];}:null;},product:function(){var px=arguments[0],qx=Array.prototype.slice.call(arguments,1),rx=[];for(var i=0;i<px.length;i++){rx.push(_.each(px[i],qx));}
return rx;},cache:function(rule){var cache={},r=null;return function(s){try{r=cache[s]=(cache[s]||rule.call(this,s));}catch(e){r=cache[s]=e;}
if(r instanceof $P.Exception){throw r;}else{return r;}};},any:function(){var px=arguments;return function(s){var r=null;for(var i=0;i<px.length;i++){if(px[i]==null){continue;}
try{r=(px[i].call(this,s));}catch(e){r=null;}
if(r){return r;}}
throw new $P.Exception(s);};},each:function(){var px=arguments;return function(s){var rx=[],r=null;for(var i=0;i<px.length;i++){if(px[i]==null){continue;}
try{r=(px[i].call(this,s));}catch(e){throw new $P.Exception(s);}
rx.push(r[0]);s=r[1];}
return[rx,s];};},all:function(){var px=arguments,_=_;return _.each(_.optional(px));},sequence:function(px,d,c){d=d||_.rtoken(/^\s*/);c=c||null;if(px.length==1){return px[0];}
return function(s){var r=null,q=null;var rx=[];for(var i=0;i<px.length;i++){try{r=px[i].call(this,s);}catch(e){break;}
rx.push(r[0]);try{q=d.call(this,r[1]);}catch(ex){q=null;break;}
s=q[1];}
if(!r){throw new $P.Exception(s);}
if(q){throw new $P.Exception(q[1]);}
if(c){try{r=c.call(this,r[1]);}catch(ey){throw new $P.Exception(r[1]);}}
return[rx,(r?r[1]:s)];};},between:function(d1,p,d2){d2=d2||d1;var _fn=_.each(_.ignore(d1),p,_.ignore(d2));return function(s){var rx=_fn.call(this,s);return[[rx[0][0],r[0][2]],rx[1]];};},list:function(p,d,c){d=d||_.rtoken(/^\s*/);c=c||null;return(p instanceof Array?_.each(_.product(p.slice(0,-1),_.ignore(d)),p.slice(-1),_.ignore(c)):_.each(_.many(_.each(p,_.ignore(d))),px,_.ignore(c)));},set:function(px,d,c){d=d||_.rtoken(/^\s*/);c=c||null;return function(s){var r=null,p=null,q=null,rx=null,best=[[],s],last=false;for(var i=0;i<px.length;i++){q=null;p=null;r=null;last=(px.length==1);try{r=px[i].call(this,s);}catch(e){continue;}
rx=[[r[0]],r[1]];if(r[1].length>0&&!last){try{q=d.call(this,r[1]);}catch(ex){last=true;}}else{last=true;}
if(!last&&q[1].length===0){last=true;}
if(!last){var qx=[];for(var j=0;j<px.length;j++){if(i!=j){qx.push(px[j]);}}
p=_.set(qx,d).call(this,q[1]);if(p[0].length>0){rx[0]=rx[0].concat(p[0]);rx[1]=p[1];}}
if(rx[1].length<best[1].length){best=rx;}
if(best[1].length===0){break;}}
if(best[0].length===0){return best;}
if(c){try{q=c.call(this,best[1]);}catch(ey){throw new $P.Exception(best[1]);}
best[1]=q[1];}
return best;};},forward:function(gr,fname){return function(s){return gr[fname].call(this,s);};},replace:function(rule,repl){return function(s){var r=rule.call(this,s);return[repl,r[1]];};},process:function(rule,fn){return function(s){var r=rule.call(this,s);return[fn.call(this,r[0]),r[1]];};},min:function(min,rule){return function(s){var rx=rule.call(this,s);if(rx[0].length<min){throw new $P.Exception(s);}
return rx;};}};var _generator=function(op){return function(){var args=null,rx=[];if(arguments.length>1){args=Array.prototype.slice.call(arguments);}else if(arguments[0]instanceof Array){args=arguments[0];}
if(args){for(var i=0,px=args.shift();i<px.length;i++){args.unshift(px[i]);rx.push(op.apply(null,args));args.shift();return rx;}}else{return op.apply(null,arguments);}};};var gx="optional not ignore cache".split(/\s/);for(var i=0;i<gx.length;i++){_[gx[i]]=_generator(_[gx[i]]);}
var _vector=function(op){return function(){if(arguments[0]instanceof Array){return op.apply(null,arguments[0]);}else{return op.apply(null,arguments);}};};var vx="each any all".split(/\s/);for(var j=0;j<vx.length;j++){_[vx[j]]=_vector(_[vx[j]]);}}());(function(){var flattenAndCompact=function(ax){var rx=[];for(var i=0;i<ax.length;i++){if(ax[i]instanceof Array){rx=rx.concat(flattenAndCompact(ax[i]));}else{if(ax[i]){rx.push(ax[i]);}}}
return rx;};Date.Grammar={};Date.Translator={hour:function(s){return function(){this.hour=Number(s);};},minute:function(s){return function(){this.minute=Number(s);};},second:function(s){return function(){this.second=Number(s);};},meridian:function(s){return function(){this.meridian=s.slice(0,1).toLowerCase();};},timezone:function(s){return function(){var n=s.replace(/[^\d\+\-]/g,"");if(n.length){this.timezoneOffset=Number(n);}else{this.timezone=s.toLowerCase();}};},day:function(x){var s=x[0];return function(){this.day=Number(s.match(/\d+/)[0]);};},month:function(s){return function(){this.month=((s.length==3)?Date.getMonthNumberFromName(s):(Number(s)-1));};},year:function(s){return function(){var n=Number(s);this.year=((s.length>2)?n:(n+(((n+2000)<Date.CultureInfo.twoDigitYearMax)?2000:1900)));};},rday:function(s){return function(){switch(s){case"yesterday":this.days=-1;break;case"tomorrow":this.days=1;break;case"today":this.days=0;break;case"now":this.days=0;this.now=true;break;}};},finishExact:function(x){x=(x instanceof Array)?x:[x];var now=new Date();this.year=now.getFullYear();this.month=now.getMonth();this.day=1;this.hour=0;this.minute=0;this.second=0;for(var i=0;i<x.length;i++){if(x[i]){x[i].call(this);}}
this.hour=(this.meridian=="p"&&this.hour<13)?this.hour+12:this.hour;if(this.day>Date.getDaysInMonth(this.year,this.month)){throw new RangeError(this.day+" is not a valid value for days.");}
var r=new Date(this.year,this.month,this.day,this.hour,this.minute,this.second);if(this.timezone){r.set({timezone:this.timezone});}else if(this.timezoneOffset){r.set({timezoneOffset:this.timezoneOffset});}
return r;},finish:function(x){x=(x instanceof Array)?flattenAndCompact(x):[x];if(x.length===0){return null;}
for(var i=0;i<x.length;i++){if(typeof x[i]=="function"){x[i].call(this);}}
if(this.now){return new Date();}
var today=Date.today();var method=null;var expression=!!(this.days!=null||this.orient||this.operator);if(expression){var gap,mod,orient;orient=((this.orient=="past"||this.operator=="subtract")?-1:1);if(this.weekday){this.unit="day";gap=(Date.getDayNumberFromName(this.weekday)-today.getDay());mod=7;this.days=gap?((gap+(orient*mod))%mod):(orient*mod);}
if(this.month){this.unit="month";gap=(this.month-today.getMonth());mod=12;this.months=gap?((gap+(orient*mod))%mod):(orient*mod);this.month=null;}
if(!this.unit){this.unit="day";}
if(this[this.unit+"s"]==null||this.operator!=null){if(!this.value){this.value=1;}
if(this.unit=="week"){this.unit="day";this.value=this.value*7;}
this[this.unit+"s"]=this.value*orient;}
return today.add(this);}else{if(this.meridian&&this.hour){this.hour=(this.hour<13&&this.meridian=="p")?this.hour+12:this.hour;}
if(this.weekday&&!this.day){this.day=(today.addDays((Date.getDayNumberFromName(this.weekday)-today.getDay()))).getDate();}
if(this.month&&!this.day){this.day=1;}
return today.set(this);}}};var _=Date.Parsing.Operators,g=Date.Grammar,t=Date.Translator,_fn;g.datePartDelimiter=_.rtoken(/^([\s\-\.\,\/\x27]+)/);g.timePartDelimiter=_.stoken(":");g.whiteSpace=_.rtoken(/^\s*/);g.generalDelimiter=_.rtoken(/^(([\s\,]|at|on)+)/);var _C={};g.ctoken=function(keys){var fn=_C[keys];if(!fn){var c=Date.CultureInfo.regexPatterns;var kx=keys.split(/\s+/),px=[];for(var i=0;i<kx.length;i++){px.push(_.replace(_.rtoken(c[kx[i]]),kx[i]));}
fn=_C[keys]=_.any.apply(null,px);}
return fn;};g.ctoken2=function(key){return _.rtoken(Date.CultureInfo.regexPatterns[key]);};g.h=_.cache(_.process(_.rtoken(/^(0[0-9]|1[0-2]|[1-9])/),t.hour));g.hh=_.cache(_.process(_.rtoken(/^(0[0-9]|1[0-2])/),t.hour));g.H=_.cache(_.process(_.rtoken(/^([0-1][0-9]|2[0-3]|[0-9])/),t.hour));g.HH=_.cache(_.process(_.rtoken(/^([0-1][0-9]|2[0-3])/),t.hour));g.m=_.cache(_.process(_.rtoken(/^([0-5][0-9]|[0-9])/),t.minute));g.mm=_.cache(_.process(_.rtoken(/^[0-5][0-9]/),t.minute));g.s=_.cache(_.process(_.rtoken(/^([0-5][0-9]|[0-9])/),t.second));g.ss=_.cache(_.process(_.rtoken(/^[0-5][0-9]/),t.second));g.hms=_.cache(_.sequence([g.H,g.mm,g.ss],g.timePartDelimiter));g.t=_.cache(_.process(g.ctoken2("shortMeridian"),t.meridian));g.tt=_.cache(_.process(g.ctoken2("longMeridian"),t.meridian));g.z=_.cache(_.process(_.rtoken(/^(\+|\-)?\s*\d\d\d\d?/),t.timezone));g.zz=_.cache(_.process(_.rtoken(/^(\+|\-)\s*\d\d\d\d/),t.timezone));g.zzz=_.cache(_.process(g.ctoken2("timezone"),t.timezone));g.timeSuffix=_.each(_.ignore(g.whiteSpace),_.set([g.tt,g.zzz]));g.time=_.each(_.optional(_.ignore(_.stoken("T"))),g.hms,g.timeSuffix);g.d=_.cache(_.process(_.each(_.rtoken(/^([0-2]\d|3[0-1]|\d)/),_.optional(g.ctoken2("ordinalSuffix"))),t.day));g.dd=_.cache(_.process(_.each(_.rtoken(/^([0-2]\d|3[0-1])/),_.optional(g.ctoken2("ordinalSuffix"))),t.day));g.ddd=g.dddd=_.cache(_.process(g.ctoken("sun mon tue wed thu fri sat"),function(s){return function(){this.weekday=s;};}));g.M=_.cache(_.process(_.rtoken(/^(1[0-2]|0\d|\d)/),t.month));g.MM=_.cache(_.process(_.rtoken(/^(1[0-2]|0\d)/),t.month));g.MMM=g.MMMM=_.cache(_.process(g.ctoken("jan feb mar apr may jun jul aug sep oct nov dec"),t.month));g.y=_.cache(_.process(_.rtoken(/^(\d\d?)/),t.year));g.yy=_.cache(_.process(_.rtoken(/^(\d\d)/),t.year));g.yyy=_.cache(_.process(_.rtoken(/^(\d\d?\d?\d?)/),t.year));g.yyyy=_.cache(_.process(_.rtoken(/^(\d\d\d\d)/),t.year));_fn=function(){return _.each(_.any.apply(null,arguments),_.not(g.ctoken2("timeContext")));};g.day=_fn(g.d,g.dd);g.month=_fn(g.M,g.MMM);g.year=_fn(g.yyyy,g.yy);g.orientation=_.process(g.ctoken("past future"),function(s){return function(){this.orient=s;};});g.operator=_.process(g.ctoken("add subtract"),function(s){return function(){this.operator=s;};});g.rday=_.process(g.ctoken("yesterday tomorrow today now"),t.rday);g.unit=_.process(g.ctoken("minute hour day week month year"),function(s){return function(){this.unit=s;};});g.value=_.process(_.rtoken(/^\d\d?(st|nd|rd|th)?/),function(s){return function(){this.value=s.replace(/\D/g,"");};});g.expression=_.set([g.rday,g.operator,g.value,g.unit,g.orientation,g.ddd,g.MMM]);_fn=function(){return _.set(arguments,g.datePartDelimiter);};g.mdy=_fn(g.ddd,g.month,g.day,g.year);g.ymd=_fn(g.ddd,g.year,g.month,g.day);g.dmy=_fn(g.ddd,g.day,g.month,g.year);g.date=function(s){return((g[Date.CultureInfo.dateElementOrder]||g.mdy).call(this,s));};g.format=_.process(_.many(_.any(_.process(_.rtoken(/^(dd?d?d?|MM?M?M?|yy?y?y?|hh?|HH?|mm?|ss?|tt?|zz?z?)/),function(fmt){if(g[fmt]){return g[fmt];}else{throw Date.Parsing.Exception(fmt);}}),_.process(_.rtoken(/^[^dMyhHmstz]+/),function(s){return _.ignore(_.stoken(s));}))),function(rules){return _.process(_.each.apply(null,rules),t.finishExact);});var _F={};var _get=function(f){return _F[f]=(_F[f]||g.format(f)[0]);};g.formats=function(fx){if(fx instanceof Array){var rx=[];for(var i=0;i<fx.length;i++){rx.push(_get(fx[i]));}
return _.any.apply(null,rx);}else{return _get(fx);}};g._formats=g.formats(["yyyy-MM-ddTHH:mm:ss","ddd, MMM dd, yyyy H:mm:ss tt","ddd MMM d yyyy HH:mm:ss zzz","d"]);g._start=_.process(_.set([g.date,g.time,g.expression],g.generalDelimiter,g.whiteSpace),t.finish);g.start=function(s){try{var r=g._formats.call({},s);if(r[1].length===0){return r;}}catch(e){}
return g._start.call({},s);};}());Date._parse=Date.parse;Date.parse=function(s){var r=null;if(!s){return null;}
try{r=Date.Grammar.start.call({},s);}catch(e){return null;}
return((r[1].length===0)?r[0]:null);};Date.getParseFunction=function(fx){var fn=Date.Grammar.formats(fx);return function(s){var r=null;try{r=fn.call({},s);}catch(e){return null;}
return((r[1].length===0)?r[0]:null);};};Date.parseExact=function(s,fx){return Date.getParseFunction(fx)(s);};


var TopMenu2 = (function() {
    var obj, cur, curNumber;
    var setting = {
	maxCloseWidth: 47,
	closeWidth: {
	    step1: 205,
	    step2: 136,
	    step3: 217,
	    step4: 154,
            step5: 150
	},
	openWidth: {
	    step1: 700,
	    step2: 700,
	    step3: 700,
	    step4: 700,
            step5: 650
	}
    }
    function initListeners() {
	var timer = 0;
	obj.find('a.open').click(function() {
	    clearTimeout(timer);
	    cur = $(this).parent().parent();
	    curNumber = cur.find('i.step').text();
	    if (curNumber == 5) {
		obj.find('li').not(cur).animate({width: setting.maxCloseWidth + 'px'}, {complete: function() {
		    //cur.animate({ width: setting.openWidth['step' + curNumber] + 'px' });
		}}).find('div.close').fadeIn().end().find('div.open').fadeOut();
		cur.animate({width: setting.openWidth['step' + curNumber] + 'px'});
	    } else {
		obj.find('li').not(cur).not('.step5').animate({width: setting.maxCloseWidth + 'px'}, {complete: function() {
		    //cur.animate({ width: setting.openWidth['step' + curNumber] + 'px' });
		}}).find('div.close').fadeIn().end().find('div.open').fadeOut();
		cur.animate({width: setting.openWidth['step' + curNumber] + 'px'});
		obj.find('.step5').animate({width: (setting.maxCloseWidth - 25) + 'px'});
		obj.find('.step5').find('div.close').fadeIn().end().find('div.open').fadeOut();
	    }
	    cur.find('div.close').fadeOut().end().find('div.open').fadeIn();
	});
	obj.find('li').hover(function() {
	    cur = $(this);
	    clearTimeout(timer);
	    timer = setTimeout(function() {
		curNumber = cur.find('i.step').text();
		if (curNumber == 5) {
		    obj.find('li').not(cur).animate({width: setting.maxCloseWidth + 'px'}, {complete: function() {
			//cur.animate({ width: setting.openWidth['step' + curNumber] + 'px' });
		    }}).find('div.close').fadeIn().end().find('div.open').fadeOut();
		    cur.animate({width: setting.openWidth['step' + curNumber] + 'px'});
		} else {
		    obj.find('li').not(cur).not('.step5').animate({width: setting.maxCloseWidth + 'px'}, {complete: function() {
			//cur.animate({ width: setting.openWidth['step' + curNumber] + 'px' });
		    }}).find('div.close').fadeIn().end().find('div.open').fadeOut();
		    cur.animate({width: setting.openWidth['step' + curNumber] + 'px'});
		    obj.find('.step5').animate({width: (setting.maxCloseWidth - 25) + 'px'});
		    obj.find('.step5').find('div.close').fadeIn().end().find('div.open').fadeOut();
		}
		cur.find('div.close').fadeOut().end().find('div.open').fadeIn();
	    }, 400);
	}, function() {
	    clearTimeout(timer);
	    timer = setTimeout(function() {
		obj.find('li').not(':last').each(function() {
		    $(this).animate({width: setting.closeWidth['step' + $(this).find('i.step').text()] + 25 + 'px'});
		});
		obj.find('li:last').animate({width: setting.closeWidth.step5 + 'px'});
		obj.find('li div.open').fadeOut().end().find('div.close').fadeIn();
		obj.find('li').not(':last').animate({'margin-right': '0'});
	    }, 1500);
	});
    }
return {
    init: function() {
	obj = $('#main-menu');
	obj.find('div.close').each(function() {
	    if ($(this).css('display') == 'none') {
		$(this).css('display', 'block').fadeOut(0);
	    }
	});
	initListeners();
    }
}})();

var salons_activity = false;

function changeFrameHeight(){
//    var height=$('#wrapper').height()+50;
//    var title=document.title;
//    var pathname=url.substr(url.indexOf('.ru')+3);
//    updater_frame.setAttribute('src', 'http://www.renault.ru/media/tools/att00309477/update.html#'+escape(title)+':::'+height+':::'+pathname);
}

jQuery.fn.maxlength = function(options) {
  // определяем параметры по умолчанию и прописываем указанные при обращении
  var settings = jQuery.extend({
    maxChars: 150 // максимальное колличество символов
  }, options);
  // выполняем плагин для каждого объекта
  return this.each(function() {
    // определяем объект
    var me = $(this);
    // определяем динамическую переменную колличества оставшихся для ввода символов
    var l = settings.maxChars;
    // определяем события на которые нужно реагировать
    me.bind('keydown keypress keyup click change',function(e) {
      // если строка больше maxChars урезаем её
      if(me.val().length>settings.maxChars) me.val(me.val().substr(0,settings.maxChars));
    });
  });
};

function nextActivity(){

             var zapolneno = true;
             $.each($('#registration-form .required'), function(){
                 if ($(this).val()==''||$(this).val()==undefined) {
                     zapolneno = false;
                 }
             });

             if (zapolneno){
                 if ($('#sogl_checkbox').length==0||$('#sogl_checkbox').attr('checked')=='checked'){
                    $('#registration-form .orange-button').removeClass('gray-disable');
                 }else{
                    $('#registration-form .orange-button').addClass('gray-disable');
                 }
             }else {
                 $('#registration-form .orange-button').addClass('gray-disable');
             }
}

//a custom format option callback
var addressFormatting = function(text){
        var newText = text;
        //array of find replaces
        var findreps = [
                {find:/^([^\-]+) \- /g, rep: '<span class="ui-selectmenu-item-header">$1</span>'},
                {find:/([^\|><]+) \| /g, rep: '<span class="ui-selectmenu-item-content">$1</span>'},
                {find:/([^\|><\(\)]+) (\()/g, rep: '<span class="ui-selectmenu-item-content">$1</span>$2'},
                {find:/([^\|><\(\)]+)$/g, rep: '<span class="ui-selectmenu-item-content">$1</span>'},
                {find:/(\([^\|><]+\))$/g, rep: '<span class="ui-selectmenu-item-footer">$1</span>'}
        ];

        for(var i in findreps){
                newText = newText.replace(findreps[i].find, findreps[i].rep);
        }
        return newText;
}

function refreshModelSelect(model_id){
    if ($('select[name="vendor_id"]').val()!=undefined&&$('select[name="vendor_id"]').val()!=''||(model_id!=''&&model_id!=undefined)){
         $('select[name="model_id"]').attr('disabled', true);
         $('select[name="model_id"] option').remove();
         $('select[name="model_id"]').append('<option value="-1">-</option>');
         $.ajax({
              url: "/api/auto/get-models/vendor_id/"+$('select[name="vendor_id"]').val(),
              dataType: 'json',
              success: function(data){
                  $.each(data.items, function(el){
                      $('select[name="model_id"]').append('<option value="'+this.id+'">'+this.title+'</option>');
                  });
                  if (model_id!=undefined){
                      $('select[name="model_id"] option[value="'+model_id+'"]').attr('selected', true);
                  }
                  $('select[name="model_id"]').attr('disabled', false);
              }
        });
    }
}

function autosalonsA(){
    $('#autosalons a').hover(function(){
        $('#autosalons a').removeClass('ui-state-hover');
        $(this).addClass('ui-state-hover');
    }, function(){

    })
    $('#autosalons a').click(function(){

        var mintime;
        var maxtime;

        var ordinary_time = $('.ordinary_time',this).html();
        if (ordinary_time!='null'){
            ordinary_time = ordinary_time.split('-');
        }
        var saturday_time = $('.saturday_time',this).html();
        if (saturday_time!='null'){
            saturday_time = saturday_time.split('-');
        }
        var sunday_time = $('.sunday_time',this).html();
        if (sunday_time!='null'){
            sunday_time = sunday_time.split('-');
        }
        if (ordinary_time!='undefined'&&saturday_time!='undefined'&&sunday_time!='undefined'){

            //отключаем нерабочие дни для выбранного салона в календаре
            if (saturday_time=='null'&&sunday_time=='null'){
                $( "#datepicker-salon" ).datepicker("option", "beforeShowDay", $.datepicker.noWeekends);
            }else if(saturday_time=='null'){
                $( "#datepicker-salon" ).datepicker("option", "beforeShowDay", noSaturday);
            }else if (sunday_time=='null'){
                $( "#datepicker-salon" ).datepicker("option", "beforeShowDay", noSunday);
            }else $( "#datepicker-salon" ).datepicker("option", "beforeShowDay", null);

            //переинициализация времени работы салона
            var selected_date = new Date($( "#datepicker-salon" ).datepicker("getDate"));           
            
            if ($.trim(sunday_time[0])=='00:00') sunday_time[0] = 0;
            if ($.trim(sunday_time[1])=='00:00') sunday_time[1] = 24;
            if ($.trim(saturday_time[0])=='00:00') saturday_time[0] = 0;
            if ($.trim(saturday_time[1])=='00:00') saturday_time[1] = 24;
            if ($.trim(ordinary_time[0])=='00:00') ordinary_time[0] = 0;
            if ($.trim(ordinary_time[1])=='00:00') ordinary_time[1] = 24;

            if (selected_date.getDay()=='0'&&sunday_time!='null'){
                if (parseInt(sunday_time[0])==sunday_time[0])
                    mintime = sunday_time[0]*60;
                else mintime = parseInt(sunday_time[0].substr(0, sunday_time[0].length-2))*60+parseInt(sunday_time[0].substr(sunday_time[0].length-2, 2));
                if (parseInt(sunday_time[1])==sunday_time[1])
                    maxtime = sunday_time[1]*60;
                else maxtime = parseInt(sunday_time[1].substr(0, sunday_time[1].length-2))*60+parseInt(sunday_time[1].substr(sunday_time[1].length-2, 2));
            }else if (selected_date.getDay()=='6'&&saturday_time!='null'){
                if (parseInt(saturday_time[0])==saturday_time[0])
                    mintime = saturday_time[0]*60;
                else mintime = parseInt(saturday_time[0].substr(0, saturday_time[0].length-2))*60+parseInt(saturday_time[0].substr(saturday_time[0].length-2, 2));
                if (parseInt(saturday_time[1])==saturday_time[1])
                    maxtime = saturday_time[1]*60;
                else maxtime = parseInt(saturday_time[1].substr(0, saturday_time[1].length-2))*60+parseInt(saturday_time[1].substr(saturday_time[1].length-2, 2));
            }else{
                if (parseInt(ordinary_time[0])==ordinary_time[0])
                    mintime = ordinary_time[0]*60;
                else mintime = parseInt(ordinary_time[0].substr(0, ordinary_time[0].length-2))*60+parseInt(ordinary_time[0].substr(ordinary_time[0].length-2, 2));
                if (parseInt(ordinary_time[1])==ordinary_time[1])
                    maxtime = ordinary_time[1]*60;
                else maxtime = parseInt(ordinary_time[1].substr(0, ordinary_time[1].length-2))*60+parseInt(ordinary_time[1].substr(ordinary_time[1].length-2, 2));
            }

            if (mintime!=undefined&&maxtime!=undefined){

                //учитываем текущее время
                if (salons_activity&&Date.today().getTime()==selected_date.getTime()){
                    var now_minutes = Date.now().getHours()*60+Date.now().getMinutes();

                    if (mintime<now_minutes){
                        //alert(now_minutes-now_minutes%30);
                        mintime = now_minutes-now_minutes%30+30;
                    }
                }

                var user_time = mintime;                


                if ($( "#slider-salon" ).slider('value')>=mintime&&$( "#slider-salon" ).slider('value')<=maxtime){
                    user_time = $( "#slider-salon" ).slider('value');
                }

                //alert('mintime '+ mintime +'maxtime '+maxtime+'user_time '+user_time);
 $( "#slider-salon" ).slider("option",{
                                min: mintime,
                                max: maxtime,
                                step: 30
                            }).slider('value', user_time);

                var t = user_time/30%2;
                var pad = '';
                if (user_time/30%2==0){
                    if (user_time/60<10) pad = '0';
                    t = pad+user_time/60+' 00';
                }
                else {
                    if (Math.floor(user_time/60)<10) pad = '0';
                    t = pad+Math.floor(user_time/60)+' 30';
                }
                $('.tablo-time').html(t);
                $( "#time-amount" ).val(t);
            }
        }else{
            $( "#slider-salon" ).slider("option",{
                                min: 0,
                                max: 1440});
            $( "#datepicker-salon" ).datepicker("option", "beforeShowDay", null);
        }

        //переинициализация даты работы салона
        var start_day = $('.start_day', this).html();
        //alert((new Date(2011, 9, start_day))>(Date.today()));
        if (start_day!='null'&&(new Date(2011, 9, start_day))>(Date.today())){
            $( "#datepicker-salon" ).datepicker("option", "minDate", new Date(2011, 9, start_day));
        }else{            
            if ((Date.today())<(new Date(2011, 9, 8)))
                $( "#datepicker-salon" ).datepicker("option", "minDate", new Date(2011, 9, 8));
            else $( "#datepicker-salon" ).datepicker("option", "minDate", Date.today());
        }

        $('#autosalons a').removeClass('ui-selectmenu-item-selected');
        $(this).addClass('ui-selectmenu-item-selected');
        $('#autosalon-select-button .ui-selectmenu-item-content').html($('.as-name',this).html());
        $('#hidden-field-autosalon').val($('.as-code',this).html());
        $('#hidden-field-promoters-time').val($('.time',this).html());
        $('.autosalon-select-button-container').hide();
         $('#autosalon-select-button').removeClass('ui-state-active');
        return false;
    });

    $('.scrolled li').hover(function(){
        $(this).addClass('scrolled-li-hover');
     }, function(){
        $(this).removeClass('scrolled-li-hover');
     })
}

function citiesA(){
    $('#cities a').hover(function(){
        $('#cities a').removeClass('ui-state-hover');
        $(this).addClass('ui-state-hover');
    }, function(){

    })

    $('#cities a').click(function(){
        $('#cities a').removeClass('ui-selectmenu-item-selected');
        $(this).addClass('ui-selectmenu-item-selected');
        $('#cities-select-button .ui-selectmenu-item-content').html($('.as-name',this).html());
        $('#hidden-field-city').val($('.as-code',this).html());
        $('.cities-select-button-container').hide();
        $('#cities-select-button').removeClass('ui-state-active');

        cschange();

        return false;
    });
}

function cschange(){
     $('#autosalons li').remove();
     $('#autosalon-select-button span span').html('АВТОСАЛОН');
     $('#hidden-field-autosalon').val('');
     if ($('#hidden-field-city').val()!=undefined){
         $.ajax({
              url: "/api/geo/get-dealers/city_id/"+$('#hidden-field-city').val(),
              dataType: 'json',
              success: function(data){
                  //console.log(data);
                  $.each(data.items, function(el){
                      $('#autosalons').append('<li><a href="#"><span class="as-name">'+this.name+'</span><span class="autosalon-address">'+this.address+'</span><span class="as-code">'+this.id+'</span><span class="time">'+this.promoters_time+'</span><span class="ordinary_time">'+this.ordinary_time+'</span><span class="saturday_time">'+this.saturday_time+'</span><span class="sunday_time">'+this.sunday_time+'</span><span class="hidden start_day">'+this.start_day+'</span></a></li>');
                  });
                  autosalonsA();
              }
        });
    }
}

function noSunday(date) {
    var dat = $.datepicker.formatDate("dd.mm.yy", date);
    if (dat=='02.10.2011'||dat=='09.10.2011'||dat=='16.10.2011'||dat=='23.10.2011'||dat=='30.10.2011')
        return [false];
    return [true];
}

function noSaturday(date) {
    var dat = $.datepicker.formatDate("dd.mm.yy", date);
    if (dat=='01.10.2011'||dat=='08.10.2011'||dat=='15.10.2011'||dat=='22.10.2011'||dat=='29.10.2011')
        return [false];
    return [true];
}


var anim_sm = 40;
function animateProcess(){
    $('.process').animate({backgroundPosition:"("+anim_sm+"px 0)"}, {duration:1, complete: function(){
          anim_sm+=1;
          animateProcess();
    }});
}
$(document).ready(function() {    
     /*заменяем шрифты*/
     flashReplace('.social h3', {'font-size': '11px'});
     $('.social h3').width(110);
     flashReplace('.h2-helvetic', {'font-size': '18px', 'height': '18px'});
     flashReplace('.h2-helvetic-big', {'font-size': '20px', 'height': '20px'});
     flashReplace('.h2-helvetic-right', {'font-size': '18px', 'text-align':'right'});
     flashReplace('h1:not(.big-h1, .thanks-h1)', {'font-size': '27px', 'margin': '10px 0 20px -3px', 'height':'27px'});
     flashReplace('h1.big-h1', {'font-size':  '50px', 'margin': '0 0 0 -3px', 'height': '50px'});

     Cufon.replace('.top-menu ul li a', {fontFamily: 'Helvetica_Neue_Condenced',  hover: true});
     Cufon.replace('#competition-menu li, .invite-info h2, .h2-helvetic-as, #prereg-error .container h2, #login-novisit-error .container h2, #login-blocked-error .container h2, #noregistered-error .container h2, #tp-popup .container h2, #thank-obr .container h2, #activation-error .container h2, .simple-info .container h2, a.black-tp, #banner-top20 p.f-r, #vosstanovit-code h2, #vosstanovit-code-tabs .ui-state-default, .process, ul.profile-menu li a, .profile-day-counter, .profile-votes-count, .profile-place, #my-photo-view h2, .no-advices-please-label, .invites-b h3, .invites-c h3, .itogi h2, .my-photo h2', {fontFamily: 'Helvetica_Neue_Condenced'});



     //включаем эффекты для раздвижного меню
     TopMenu2.init();

     //прозрачность фоток победителей
     $('.winners ul li .photo img').css("opacity", "0.5").hover(function(){
                    $(this).css("opacity", "1");
                }, function(){
                    $(this).css("opacity", "0.5");
                });

     //зум фоток победителей
     $('.winners ul a').click(function(){
         var index = $(this).parent().parent().index();

         PrizeGallery.setCurrent(index);

         //window.parent.$('#how').css('height','1300px');

         $('#prizes-gallery .photos img').hide();
         $('#prizes-gallery .photos img:eq('+index+')').show();

         $('.cool-stories .story').hide();
         $('.cool-stories .story:eq('+index+')').show();
         if (index==0) {
             $('#prizes-prev').hide();
             $('#prizes-next').show();
         }
         else if (index==$('.winners ul li').length-1) {
             $('#prizes-prev').show();
             $('#prizes-next').hide();
         }
         else {
             $('#prizes-prev').show();
             $('#prizes-next').show();
         }

         $('#winner-zoom').show();
         changeFrameHeight();
         return false;
     })

     $('#winner-zoom a.close').click(function() {
		$('#winner-zoom').hide();
	    });

     //имитация placeholder
     $('#preregistration input[type="text"], #friend-email, #profile-registered input[type="text"]').focus(function(){
        $(this).addClass('black-text');
     })
     $('#preregistration input[type="text"],  #profile-registered input[type="text"]').blur(function(){
        if ($(this).val()=='') $(this).removeClass('black-text');
     })
     $('#friend-email').blur(function(){
        if ($(this).val()=='') $(this).removeClass('black-text');
     })

     var s_clear = true;
     $('#header-search').mousedown(function(){
        if (s_clear){
            $('#header-search').val('');
            s_clear = false;
        }
     });

     var s_clear2 = true;
     if ($('#family').hasClass('real-value')) s_clear2 = false
     $('#family').mousedown(function(){
        if (s_clear2){
            $('#family').val('');
            s_clear2 = false;
        }
     }).blur(function(){
         if ($(this).val()=='') {
             s_clear2 = true;
             $(this).val('Фамилия');
         }
     });

     var s_clear3 = true;
     if ($('#name').hasClass('black-text')) s_clear3 = false;
     $('#name').mousedown(function(){
        if (s_clear3){
            $('#name').val('');
            s_clear3 = false;
        }
     }).blur(function(){
         if ($(this).val()=='') {
             s_clear3 = true;
             $(this).val('Имя');
         }
     });

     var s_clear4 = true;
     if ($('#surname').hasClass('black-text')) s_clear4 = false;
     $('#surname').mousedown(function(){
        if (s_clear4){
            $('#surname').val('');
            s_clear4 = false;
        }
     }).blur(function(){
         if ($(this).val()=='') {
             s_clear4 = true;
             $(this).val('Отчество');
         }
     });

     var s_clear5 = true;
     if ($('#city').hasClass('black-text')) s_clear5 = false;
     $('#city').mousedown(function(){
        if (s_clear5){
            $('#city').val('');
            s_clear5 = false;
        }
     }).blur(function(){
         if ($(this).val()=='') {
             s_clear5 = true;
             $(this).val('Город');
         }
     });

     var s_clear6 = true;
     if ($('#friend-email').hasClass('black-text')) s_clear6 = false;
     $('#friend-email').mousedown(function(){
        if (s_clear6){
            $('#friend-email').val('');
            s_clear6 = false;
        }
     }).blur(function(){
         if ($(this).val()=='') {
             s_clear6 = true;
             $(this).val('ВВЕДИТЕ E-MAIL ДРУГА');
         }
     });


     //окно с ошибкой - такой e-mail уже зарегистрирован
     //$('#prereg-error').show();
     $('#prereg-error a.close').click(function() {
		$('#prereg-error').hide();
                $('#pre-reg-email').focus();
	    });

     // отправить еще раз
     $('#send_again_button').click(function() {
        $.post('/profile/pre-registration/send-again','', function(){
            $('#send_again_button').html('ОТПРАВЛЕНО');
            setTimeout(function(){
                $('#send_again_button').html('ОТПРАВИТЬ ЕЩЕ РАЗ');
            }, 30000);
        }, 'json');
        return false;
     });

     // отправить еще раз со странице registered
     $('#registered_send_again_button').click(function() {
        $.post('/profile/registered/send-again','', function(){
            $('#registered_send_again_button').html('ОТПРАВЛЕНО');
            setTimeout(function(){
                $('#registered_send_again_button').html('ОТПРАВИТЬ ЕЩЕ РАЗ');
            }, 30000);
        }, 'json');
        return false;
     });

     // указать другой email
     $('#other_email_button').click(function(){
        $('.pre-reg-success').hide();
        $('.pre-reg-form').show();
        $('#pre-reg-email').val('').focus();
     });


     $('#pre-register-form').ajaxForm({
            dataType: 'json',
            beforeSubmit: function(){
                 if ($('#pre-register-form .orange-button').hasClass('process'))
                     return false;
                 if (!Form.isValidEmail($('#pre-reg-email').val())){
                     $('#pre-reg-email').addClass('red-border-error').focus().keydown(function(){
                        $(this).removeClass('red-border-error');
                     });
                     $('#pre-register-form p.error').show();
                     return false;
                 }else{
                     $('#pre-register-form .orange-button').addClass('process');
                     animateProcess();
                     return true;
                 }
            },
            success: function(data, status) {
                switch (data.code){
                    case 200:
                        $('.pre-reg-form').hide();
                        $('.pre-reg-success').show();
                        break;
                    case 601:
                        $('#pre-reg-email').addClass('red-border-error').focus().keydown(function(){
                            $(this).removeClass('red-border-error');
                         });
                        $('#pre-register-form p.error').show();
                        break;
                    case 602:
                        $('#prereg-error').show();
                        break;
                }
                $('#pre-register-form .orange-button').removeClass('process').stop().css({backgroundPosition: '100% 0'});
            },
            error: function(XHR) {
                $('#pre-register-form .orange-button').removeClass('process').stop().css({backgroundPosition: '100% 0'});
                alert('Не удалось выполнить проверку e-mail, попробуйте позже!')
            }
        });
     if ($('#pre-reg-email')){
         $('#pre-reg-email').focus();
         $('#pre-reg-email').keydown(function(){
             $('#pre-register-form p.error').hide();
         })
     }

     //изменяем вид радиокнопок и чекбоксов
     //$('.myjqtransform').jqTransform({imgPath:'/i/jqtransformplugin/'});

     //изменяем вид списков
     if ($('#model-select').length){
         $('#model-select').selectmenu({
             style:'dropdown',
             maxHeight: 150
         });
     }
//     if ($('#vendor-select').length){
//         $('#vendor-select').selectmenu({
//             style:'dropdown',
//             maxHeight: 150,
//             change: refreshModelSelect
//         });
//         refreshModelSelect();
//     }

     //refreshModelSelect();

     $('.gray-select').selectmenu({style:'dropdown',maxHeight: 150});

     if ($('#autosalon-select').length){
         $('#autosalon-select').selectmenu({
                style:'dropdown',
                menuWidth: 195,
                maxHeight: 150,
                format: addressFormatting
        });
    }

    $('#autosalon-select-button').click(function(){
        if ($('.autosalon-select-button-container').is(':visible')){
            $('.autosalon-select-button-container').hide();
            $(this).removeClass('ui-state-active');
        }else{
             $('.autosalon-select-button-container').show();
             $('.autosalon-select-button-container .scroll-pane').jScrollPane();
             $(this).addClass('ui-state-active');
        }
        return false;
    })

    //захлопываем списки при клике вне области
    $('body').click(function(){
        if ($('.autosalon-select-button-container').is(':visible')){
             $('.autosalon-select-button-container').hide();
             $('#autosalon-select-button').removeClass('ui-state-active');
        }
        if ($('.cities-select-button-container').is(':visible')){
             $('.cities-select-button-container').hide();
             $('#cities-select-button').removeClass('ui-state-active');
        }
        if ($('.dob-day-select-button-container').is(':visible')){
             $('.dob-day-select-button-container').hide();
             $('#dob-day-select-button').removeClass('ui-state-active');
        }
        if ($('.dob-month-select-button-container').is(':visible')){
                $('.dob-month-select-button-container').hide();
                $('#dob-month-select-button').removeClass('ui-state-active');
            }
        if ($('.dob-year-select-button-container').is(':visible')){
                $('.dob-year-select-button-container').hide();
                $('#dob-year-select-button').removeClass('ui-state-active');
            }
        if ($('.year-select-button-container').is(':visible')){
                $('.year-select-button-container').hide();
                $('#year-select-button').removeClass('ui-state-active');
            }
        if ($('.vendor-select-button-container').is(':visible')){
                $('.vendor-select-button-container').hide();
                $('#vendor-select-button').removeClass('ui-state-active');
            }
        if ($('.model-select-button-container').is(':visible')){
                $('.model-select-button-container').hide();
                $('#model-select-button').removeClass('ui-state-active');
            }
    })

    $('#cities-select-button').click(function(){
        if ($('.autosalon-select-button-container').is(':visible')){
             $('.autosalon-select-button-container').hide();
             $('#autosalon-select-button').removeClass('ui-state-active');
        }
    })
    autosalonsA();

    if ($('#cities-select-button').length){
        $('#cities-select-button').click(function(){
            if ($('.cities-select-button-container').is(':visible')){
                 $('.cities-select-button-container').hide();
                $(this).removeClass('ui-state-active');
            }else{
                 $('.cities-select-button-container').show();
                 $('.cities-select-button-container .scroll-pane').jScrollPane();
                 $(this).addClass('ui-state-active');
            }
            return false;
        })
        cschange();
        citiesA();
    }

    //выпадающий список марок
    $('select[name="vendor_id"]').change(function(){
        refreshModelSelect();
    })

    // отсылаем sms с кодом на указанный номер
    $('#getSmsCodeButton').click(function(){
        if (!$(this).hasClass('gray-disable')){
            var phone = $('#phone-short-code').val()+$('#phone-number').val();
            if (phone.length != 10 || phone != parseInt(phone)) {
                $('#phone-short-code').addClass('red-border-error').keydown(function(){
                                $(this).removeClass('red-border-error');
                             });
                $('#phone-number').addClass('red-border-error').keydown(function(){
                                $(this).removeClass('red-border-error');
                             });
            } else {
                $('#phone-short-code').removeClass('red-border-error');
                $('#phone-number').removeClass('red-border-error');
                //$('#getSmsCodeButton').hide();
                $('#getSmsCodeButton').addClass('gray-disable');
                $.post('/profile/pre-registration/sms-code-send',{'phone':phone}, function(data){
                    // @todo remove sms_code
                    if(data.code == 603){   //если телефон уже зарегистирован в системе
                        $('#phone-reg-error').show();
                        $('#phone-short-code').addClass('red-border-error');
                        $('#phone-number').addClass('red-border-error');
                        $('#getSmsCodeButton').removeClass('gray-disable');
                    }else{
                        //$('<span id="smsCodeSuccess">SMS с кодом подтверждения отправлено</span>').insertAfter('#getSmsCodeButton');
                        $('#sms-sended-info').show();
                        setTimeout(function(){
                            //$('#smsCodeSuccess').remove();
                            $('#getSmsCodeButton').removeClass('gray-disable');
                        }, 180000);
                    }
                }, 'json');
            }
        }
        return false;
    });

    // проверяем код подтверждения
    $('#checkPhoneButton').click(function(){
        var has_error = false;
        var phone = $('#phone-short-code').val()+$('#phone-number').val();
        var sms_code = $('#code-podtv').val();
        if (phone.length != 10 || phone != parseInt(phone)) {
            $('#phone-short-code').addClass('red-border-error').keydown(function(){
                            $(this).removeClass('red-border-error');
                         });
            $('#phone-number').addClass('red-border-error').keydown(function(){
                            $(this).removeClass('red-border-error');
                         });
            has_error = true;
        }
        if (!sms_code) {
            $('#code-podtv').addClass('red-border-error').keydown(function(){
                            $(this).removeClass('red-border-error');
                         });
            has_error = true;
        }
        if (!has_error) {
            $('#checkPhoneButton').hide();
            $.post('/profile/pre-registration/sms-code-check', {'sms_code':sms_code}, function(data){
               if (data.code == 200 && data.message == 'OK') {
                    $('#phone-short-code').attr('readonly', 'readonly');
                    $('#phone-number').attr('readonly', 'readonly');
                    $('#code-podtv-div').hide();
                    $('#getSmsCodeButton').hide();
                    //$('#smsCodeSuccess').html('Телефон подтвержден');

                    $('.nepodtv_phone, .phone-code, #smsCodeSuccess, #getSmsCodeButton').hide();
                    $('#podtv_phone').val('+7 '+$('#phone-short-code').val()+' '+$('#phone-number').val())
                                     .show();
                     $('.podtv_phone').show();
               } else{
                    $('#checkPhoneButton').show();
                    $('#code-podtv').addClass('red-border-error').keydown(function(){
                            $(this).removeClass('red-border-error');
                         });
               }
            }, 'json');
        }

        return false;
    });

    $('#registeredGetSmsCodeButton').click(function(){
        if (!$(this).hasClass('gray-disable')){
            var phone = $('#phone-short-code').val()+$('#phone-number').val();
            if (phone.length != 10 || phone != parseInt(phone)) {
                $('#phone-short-code').addClass('red-border-error').keydown(function(){
                                $(this).removeClass('red-border-error');
                             });
                $('#phone-number').addClass('red-border-error').keydown(function(){
                                $(this).removeClass('red-border-error');
                             });
            } else {
                $('#phone-short-code').removeClass('red-border-error');
                $('#phone-number').removeClass('red-border-error');
                //$('#registeredGetSmsCodeButton').hide();
                $('#registeredGetSmsCodeButton').addClass('gray-disable');
                $.post('/profile/registered/sms-code-send',{'phone':phone}, function(data){
                    // @todo remove sms_code
                    if(data.code == 603){   //если телефон уже зарегистирован в системе
                        $('#phone-reg-error').show();
                        $('#phone-short-code').addClass('red-border-error');
                        $('#phone-number').addClass('red-border-error');
                        $('#registeredGetSmsCodeButton').removeClass('gray-disable');
                    }else{
                        //$('<span id="smsCodeSuccess">SMS с кодом подтверждения отправлено</span>').insertAfter('#registeredGetSmsCodeButton');
                        $('#sms-sended-info').show();
                        setTimeout(function(){
                            //$('#smsCodeSuccess').remove();
                            $('#registeredGetSmsCodeButton').removeClass('gray-disable');
                        }, 180000);
                    }
                }, 'json');
            }
        }
        return false;
    });

    $('#registeredCheckPhoneButton').click(function(){
        var has_error = false;
        var phone = $('#phone-short-code').val()+$('#phone-number').val();
        var sms_code = $('#code-podtv').val();
        if (phone.length != 10 || phone != parseInt(phone)) {
            $('#phone-short-code').addClass('red-border-error').keydown(function(){
                            $(this).removeClass('red-border-error');
                         });
            $('#phone-number').addClass('red-border-error').keydown(function(){
                            $(this).removeClass('red-border-error');
                         });
            has_error = true;
        }
        if (!sms_code) {
            $('#code-podtv').addClass('red-border-error').keydown(function(){
                            $(this).removeClass('red-border-error');
                         });
            has_error = true;
        }
        if (!has_error) {
            $('#registeredCheckPhoneButton').hide();
            $.post('/profile/registered/sms-code-check', {'sms_code':sms_code, 'phone':phone}, function(data){
               if (data.code == 200 && data.message == 'OK') {
                    $('#phone-short-code').attr('readonly', 'readonly');
                    $('#phone-number').attr('readonly', 'readonly');
                    $('#code-podtv-div').hide();
                    $('#registeredGetSmsCodeButton').hide();
                    //$('#smsCodeSuccess').html('Телефон подтвержден');

                    $('.nepodtv_phone, .phone-code, #smsCodeSuccess, #registeredGetSmsCodeButton').hide();
                    $('#podtv_phone').val('+7 '+$('#phone-short-code').val()+' '+$('#phone-number').val())
                                     .show();
                     $('.podtv_phone').show();
               } else{
                    $('#registeredCheckPhoneButton').show();
                    $('#code-podtv').addClass('red-border-error').keydown(function(){
                            $(this).removeClass('red-border-error');
                         });
               }
            }, 'json');
        }

        return false;
    });


    //ajax'овая форма регистрации
    if ($('#registration-form')&&!$('#registration-form').hasClass('no-ajax')){
        $('#registration-form').ajaxForm({
            dataType: 'json',
            beforeSerialize: function($form, options) {
                $('#birthday').val($('select[name="dob-day"]').val()+'.'+$('select[name="dob-month"]').val()+'.'+$('select[name="dob-year"]').val());
                $('#phone').val('+7'+$('#phone-short-code').val()+$('#phone-number').val());
            },

            beforeSubmit: function(){
                     if ($('#registration-form .orange-button').hasClass('process')||$('#registration-form .orange-button').hasClass('gray-disable2'))
                        return false;
                     var has_error = false;
                     $.each($('.required'), function(){
                         if ($(this).val()==''||!$(this).hasClass('black-text')){
                             has_error = true;
                             $(this).addClass('red-border-error').keydown(function(){
                                $(this).removeClass('red-border-error');
                             });
                         }
                     })
                     if ($('#new-email').val()!=''&&!Form.isValidEmail($('#new-email').val())){
                         has_error = true;
                         $('#new-email').addClass('red-border-error').keydown(function(){
                            $(this).removeClass('red-border-error');
                         });
                     }
                     if ($('#sogl_checkbox').length&&$('#sogl_checkbox').attr('checked')!='checked'){
                         has_error = true;
                         $('#sogl_label').addClass('error-colored');
                         $('#sogl_checkbox').click(function(){
                                $('#sogl_label').removeClass('error-colored');
                            });
                     }
                     if (has_error){
                         return false;
                     }else{

                         $('#registration-form .orange-button').addClass('process');
                         animateProcess();
                         return true;
                     }
                },
            success: function(data, status) {
                switch (data.code){
                    case 200:
                        $(location).attr('href', '/profile/pre-registration/notification/');
                        break;
                    case 0:
                        $('#prereg-error').show();
                        break;
                    case 603:
                        $('#phone-reg-error').show();  // Если человек вбил уже существующий в БД телефон, не подтвердил его и пытается перейти дальше, то сервер выдаёт ошибку 603, и должен показываться поп-ап "ТАКОЙ ТЕЛЕФОН УЖ ЕСТЬ В БАЗЕ"
                        $('#phone-short-code').addClass('red-border-error');
                        $('#phone-number').addClass('red-border-error');
                        $('#getSmsCodeButton').show();
                        break;
                    default:
                        alert('Ошибка! Попробуйте позже!')
                        break;
                }
                $('#registration-form .orange-button').removeClass('process').stop();
                if ($('#registration-form .orange-button').hasClass('next-button')){
                        $('#registration-form .orange-button').css({backgroundPosition: '100% 0'});
                    }else{
                        $('#registration-form .orange-button').css({backgroundPosition: '50% 0'});
                    }
            },
            error: function(XHR) {
                 $('#registration-form .orange-button').removeClass('process').stop();
                 if ($('#registration-form .orange-button').hasClass('next-button')){
                        $('#registration-form .orange-button').css({backgroundPosition: '100% 0'});
                    }else{
                        $('#registration-form .orange-button').css({backgroundPosition: '50% 0'});
                    }
                alert('Ошибка! Попробуйте позже!');
            }
        });

    }else{
        $('#registration-form').submit(function(){
            var has_error = false;
            if ($('#registration-form .orange-button').hasClass('gray-disable2'))
                has_error = true;
             $.each($('.required'), function(){
                 if ($(this).val()==''||!$(this).hasClass('black-text')){
                     has_error = true;
                     $(this).addClass('red-border-error').keydown(function(){
                        $(this).removeClass('red-border-error');
                     });
                 }
             })
             if ($('#new-email').val()!=''&&!Form.isValidEmail($('#new-email').val())){
                 has_error = true;
                 $('#new-email').addClass('red-border-error').keydown(function(){
                    $(this).removeClass('red-border-error');
                 });
             }
             if ($('#sogl_checkbox').length&&$('#sogl_checkbox').attr('checked')!='checked'){
                 has_error = true;
                 $('#sogl_label').addClass('error-colored');
                 $('#sogl_checkbox').click(function(){
                        $('#sogl_label').removeClass('error-colored');
                    });
             }
             if (has_error){
                 return false;
             }else{
                 $('#birthday').val($('select[name="dob-day"]').val()+'.'+$('select[name="dob-month"]').val()+'.'+$('select[name="dob-year"]').val());
                 $('#phone').val('+7'+$('#phone-short-code').val()+'.'+$('#phone-number').val());

                 return true;
             }
        })
    }

    //календарь    
    var dp_mindate = new  Date(2011, 9, 8);
    if (Date.today()>=dp_mindate){
        salons_activity = true;
        dp_mindate = Date.today();
    }
    $( "#datepicker-salon" ).datepicker({
        minDate: dp_mindate,
        maxDate: new Date(2011, 9, 23),
        altField: "#hidden-field-date",
        constrainInput: true,
        onSelect: function(){
            //alert('!');
            $('#autosalons a.ui-selectmenu-item-selected').click();
        }
    });

    //слайдер
    $( "#slider-salon" ).slider({
			value:1110,
			min: 0,
			max: 1440,
			step: 30,
			slide: function( event, ui ) {
                            var t = ui.value/30%2;
                            var pad = '';
                            if (ui.value/30%2==0){
                                if (ui.value/60<10) pad = '0';
                                t = pad+ui.value/60+' 00';
                            }
                            else {
                                if (Math.floor(ui.value/60)<10) pad = '0';
                                t = pad+Math.floor(ui.value/60)+' 30';
                            }
                            $('.tablo-time').html(t);
                            $( "#time-amount" ).val(t);
			}
		});

    //хинты
    $('#phone-short-code, #phone-number, #code-podtv').focus(function(){

        $('#'+$(this).attr('id')+'-tooltip').show().offset({top: $(this).offset().top+$(this).height()+12, left: $(this).offset().left});
    }).blur(function(){
        $('#'+$(this).attr('id')+'-tooltip').hide()
    });

    //ввод кода доступа в ЛК
    $('#login-form').ajaxForm({
            dataType: 'json',
            beforeSubmit: function(){
                if ($('#login-form .orange-button').hasClass('process')){
                        return false;
                        }
                if ($('#login-code').val()==''){
                    $('#login-code').addClass('red-border-error').focus().keydown(function(){
                            $(this).removeClass('red-border-error');
                         });
                    return false;
                }
                $('#login-form .orange-button').addClass('process');
                 animateProcess();
            },
            success: function(data, status) {
                switch (data.code){
                    case 401:
                        $('#login-code').addClass('red-border-error').focus().keydown(function(){
                            $(this).removeClass('red-border-error');
                         });
                        break;
                    case 403: //человек, который ещё не сфотографировался. Должен получить ошибку при входе и сообщение, что надо прийти в салон и сфоткаться
                        //$(location).attr('href', '/profile/registered/info/');
                        $('#login-novisit-error').show();
                        break;
                    case 407:
                        $('#login-blocked-error').show();
                        break;
                    case 200:
                        $(location).attr('href', '/profile/registered/confirm-info/');
                        break;
                    case 601:
                        $('#login-code').addClass('red-border-error').focus().keydown(function(){
                            $(this).removeClass('red-border-error');
                         });
                        $('#login-form').show();
                        break;
                }
                $('#login-form .orange-button').removeClass('process').stop().css({backgroundPosition: '0 0'});
            },
            error: function(XHR) {
                alert('Не удалось выполнить проверку кода, попробуйте позже!')
            }
        });

     if ($('#login-code')){
         $('#login-code').focus();
         $('#login-code').keydown(function(){
             $('#login-form p.error').hide();
         })
     }

     //окно "неверный код"
     //$('#login-novisit-error').show();
     $('#login-novisit-error a.close').click(function() {
        $('#login-novisit-error').hide();
     });

     //окно "вы не были в салоне"
     $('#login-novisit-error-2 a.close').click(function() {
        $('#login-novisit-error-2').hide();
     });

     //окно "доступ в личный кабинет заблокирован за нарушение условий конкурса"
     //$('#login-blocked-error').show();
     $('#login-blocked-error a.close').click(function() {
        $('#login-blocked-error').hide();
     });

     //окно "восстановить код доступа"
     $('#vosstanovlenie').click(function(){
          $('#vosstanovit-code').show();
          return false;
     })
     $('#vosstanovit-code a.close').click(function() {
        $('#vosstanovit-code').hide();
     });
     $( "#vosstanovit-code-tabs" ).tabs();
     $('#vosstanovit-code-tabs li a').click(function(){
         Cufon.replace('#vosstanovit-code-tabs .ui-state-default', {fontFamily: 'Helvetica_Neue_Condenced'});
     })

     $('#vosstanovlenie-form').ajaxForm({
        dataType: 'json',
        beforeSubmit: function(){
                if ($('#vosstanovlenie-form .black-tp').hasClass('process'))
                        return false;
                 var has_error = false;
                 if (!Form.isValidEmail($('#vosst_email').val())){
                     has_error = true;
                     $('#vosst_email').addClass('red-border-error').keydown(function(){
                        $(this).removeClass('red-border-error');
                        $('#vosstanovlenie-form .error').hide();
                     }).focus();
                     $('#vosstanovlenie-form .error').show();
                 }
                 if ($('.bil_v_salone', $('#vosstanovlenie-form')).attr('checked')!='checked') {
                        has_error = true;
                        $('.bil_v_salone-label', $('#vosstanovlenie-form')).addClass('error-colored').click(function(){
                            $('.bil_v_salone-label', $('#vosstanovlenie-form')).removeClass('error-colored');
                        });
                        $('.bil_v_salone', $('#vosstanovlenie-form')).click(function(){
                            $('.bil_v_salone-label', $('#vosstanovlenie-form')).removeClass('error-colored');
                        });
                 }
                 if (has_error){
                     return false;
                 }else{
                     //$('#vosstanovlenie-form .black-tp').hide();
                     $('#vosstanovlenie-form .black-tp').addClass('process');
                     animateProcess();
                     //$('#vosstanovlenie-form .process').show();
                     return true;
                 }
            },
        success: function(data, status) {
            switch (data.code){
                case 200:
                    $('#wait-message').show();
                    break;
                case 613: //На 613 надо показывать "Вы не были в салоне"
                        $('#login-novisit-error-2').show();
                        break;
                default:
                    $('#error-message-text').text(data.error);
                    $('#vosstanovlenie-error').show();
                    break;
            }
            $('#vosstanovlenie-form .black-tp').removeClass('process').stop();
            $('#vosstanovit-code').hide();

        },
        error: function(XHR) {
            $('#vosstanovlenie-form .black-tp').removeClass('process').stop();
            alert('Ошибка! Попробуйте позже!');
            //$('#vosstanovlenie-form .process').hide();
            //$('#vosstanovlenie-form .black-tp').show();
        }
    });
    $('#vosstanovlenie-form .black-tp').click(function(){
        $('#vosstanovlenie-form').submit();
        return false;
    });

    $('#vosstanovlenie').click(function(){
          $('#vosstanovit-code').show();
          return false;
     })
     $('#vosstanovit-code a.close').click(function() {
        $('#vosstanovit-code').hide();
     });
     $( "#vosstanovit-code-tabs" ).tabs();
     $('#vosstanovit-code-tabs li a').click(function(){
         Cufon.replace('#vosstanovit-code-tabs .ui-state-default', {fontFamily: 'Helvetica_Neue_Condenced'});
     })

     $('#vosstanovlenie-form-2').ajaxForm({
        dataType: 'json',
        beforeSubmit: function(){
                 if ($('#vosstanovlenie-form-2 .black-tp').hasClass('process'))
                        return false;
                 var has_error = false;
                 if ($('.bil_v_salone', $('#vosstanovlenie-form-2')).attr('checked')!='checked') {
                        has_error = true;
                        $('.bil_v_salone-label', $('#vosstanovlenie-form-2')).addClass('error-colored').click(function(){
                            $('.bil_v_salone-label', $('#vosstanovlenie-form-2')).removeClass('error-colored');
                        });
                        $('.bil_v_salone', $('#vosstanovlenie-form-2')).click(function(){
                            $('.bil_v_salone-label', $('#vosstanovlenie-form-2')).removeClass('error-colored');
                        });
                 }
                 $.each($('.high-input'), function(){
                     if ($(this).val()==''){
                         $(this).addClass('red-border-error').keydown(function(){
                            $(this).removeClass('red-border-error');
                         });
                         has_error = true;
                     }
                 })
                 if (has_error){
                     return false;
                 }else{
                     //$('#vosstanovlenie-form-2 .black-tp').hide();
                     //$('#vosstanovlenie-form-2 .process').show();
                     $('#vosstanovlenie-form-2 .black-tp').addClass('process');
                     animateProcess();
                     return true;
                 }
            },
        success: function(data, status) {
            switch (data.code){

                case 200:
                    $('#wait-message').show();
                    break;
                case 613: //На 613 надо показывать "Вы не были в салоне"
                    $('#login-novisit-error-2').show();
                    break;
                 default:
                    $('#error-message-text').text(data.error);
                    $('#vosstanovlenie-error').show();
                    break;
            }
            //$('#vosstanovlenie-form-2 .process').hide();
            //$('#vosstanovlenie-form-2 .black-tp').show();
            $('#vosstanovlenie-form-2 .black-tp').removeClass('process').stop();
            $('#vosstanovit-code').hide();

        },
        error: function(XHR) {
            alert('Ошибка! Попробуйте позже!');
            $('#vosstanovlenie-form-2 .process').hide();
            $('#vosstanovlenie-form-2 .black-tp').show();
        }
    });
    $('#vosstanovlenie-form-2 .black-tp').click(function(){
        $('#vosstanovlenie-form-2').submit();
        return false;
    })

    if ($('.process').length)
        animateProcess();

    //окно "такой e-mail не зарегистрирован"
    //$('#login-novisit-error').show();
    $('#noregistered-error a.close').click(function() {
        $('#noregistered-error').hide();
    });

    //окно "связаться со службой поддержки"
    //$('#tp-popup').show();
    $('#tp-popup a.close').click(function() {
        $('#tp-popup').hide();
     });

     $('#tp-popup a.black-tp').click(function(){
         $('#tp-form').submit();
         return false;
     })

     $('#tp-form').ajaxForm({
        dataType: 'json',
        beforeSubmit: function(){
                if ($('#tp-form .black-tp').hasClass('process'))
                        return false;
                 var has_error = false;
                 if ($('input', $('#tp-form')).val()=='') {
                        has_error = true;
                        $('input', $('#tp-form')).addClass('red-border-error').keydown(function(){
                            $(this).removeClass('red-border-error');
                         });
                 }
                 if ($('textarea', $('#tp-form')).val()=='') {
                        has_error = true;
                        $('textarea', $('#tp-form')).addClass('red-border-error').keydown(function(){
                            $(this).removeClass('red-border-error');
                         });
                 }
                 if (has_error){
                     return false;
                 }else{
                     $('#tp-form .black-tp').addClass('process');
                     animateProcess();
                     return true;
                 }
            },
        success: function(data, status) {
            switch (data.code){

                case 200:

                    break;
                default:
                    //alert('Ошибка! Попробуйте позже!')
                    break;
            }
            $('#tp-form .black-tp').removeClass('process').stop();
            $('#thank-obr').show();
        },
        error: function(XHR) {
            $('#tp-form .black-tp').removeClass('process').stop();
            alert('Ошибка! Попробуйте позже!');
        }
    });
    $('.show-tp').click(function(){
        $(this).closest("div.container").parent().hide();
        $('#tp-popup').show();
        return false;
    })

    $('.show-tp-2').click(function(){
        $('#tp-popup').show();
        return false;
    })

    //окно "спасибо за обращение"
    //$('#thank-obr').show();
    $('#thank-obr a.close').click(function() {
        $('#thank-obr').hide();
     });

     //подтверждение e-mail
     $('#activation-form').ajaxForm({
            dataType: 'json',
            beforeSubmit: function(){
                if ($('#activation-form .orange-button').hasClass('process'))
                        return false;
                 if (!Form.isValidEmail($('#activation-email').val())){
                     $('#activation-email').addClass('red-border-error').focus().keydown(function(){
                        $(this).removeClass('red-border-error');
                     });
                     $('#activation-form p.error').show();
                     return false;
                 }else{
                     $('#activation-form .orange-button').addClass('process');
                     animateProcess();
                     return true;
                 }
            },
            success: function(data, status) {
                switch (data.code){
                    case 200:
                        $('.activation-form').hide();
                        $('.activation-success').show();
                        break;
                    case 601:
                        $('#activation-email').addClass('red-border-error').focus().keydown(function(){
                            $(this).removeClass('red-border-error');
                         });
                        $('#activation-form p.error').show();
                        break;
                    case 602:
                        $('#activation-error').show();
                        break;
                }
                $('#activation-form .orange-button').removeClass('process').stop();
                $('#activation-form .orange-button').css({backgroundPosition: '100% 0'});
            },
            error: function(XHR) {
                $('#activation-form .orange-button').removeClass('process').stop();
                $('#activation-form .orange-button').css({backgroundPosition: '100% 0'});
                alert('Не удалось выполнить проверку e-mail, попробуйте позже!')
            }
        });


     if ($('#activation-email')){
         $('#activation-email').focus();
         $('#activation-email').keydown(function(){
             $('#activation-form p.error').hide();
         })
     }

     //форма "продолжите фразу"
     $('#make-photo-form-button').click(function(){
         if ($('.active-bonus-message').length==0)
            $('#make-photo-form').submit();
        else{
            var has_error = false;
             if ($('input[name="soglasie"]', $('#make-photo-form')).attr('checked')!='checked') {
                    has_error = true;
                    $('label', $('#make-photo-form')).addClass('error-colored').click(function(){
                        $('label', $('#make-photo-form')).removeClass('error-colored');
                    });
                    $('input[name="soglasie"]', $('#make-photo-form')).click(function(){
                        $('label', $('#make-photo-form')).removeClass('error-colored');
                    });
             }
             if (!has_error){
                 $('.active-bonus-message').show();
             }
        }
         return false;
     })
     $('#make-photo-form').submit(function(){
         var has_error = false;
         if ($('input[name="soglasie"]', $('#make-photo-form')).attr('checked')!='checked') {
                has_error = true;
                $('label', $('#make-photo-form')).addClass('error-colored').click(function(){
                    $('label', $('#make-photo-form')).removeClass('error-colored');
                });
                $('input[name="soglasie"]', $('#make-photo-form')).click(function(){
                    $('label', $('#make-photo-form')).removeClass('error-colored');
                });
         }
         if (has_error){
             return false;
         }else{
             var top = $('#photo-slogan').css('top');
             if (top=='auto') top = 0;
             else{
                 top = top.substr(0, top.length-2);
             }
             var left = $('#photo-slogan').css('left');
             if (left=='auto') left = 0;
             else{
                 left = left.substr(0, left.length-2);
             }
             $('#coordinates').val(left+':'+top);
             return true;
         }
     })


        //перемещение слогана по фотке
        $( "#photo-slogan" ).draggable({containment: "parent"});

        //окно bonus-ok
        //$('#bonus-ok').show();
        $('#bonus-ok a.close').click(function() {
            $('#bonus-ok').hide();
            $('#make-photo-form').submit();
         });

        //окно bonus-fail
        //$('#bonus-fail').show();
        $('#bonus-fail a.close').click(function() {
            $('#bonus-fail').hide();
            $('#make-photo-form').submit();
        });

        //окно "проголосовать"
        //$('#plus-odin').show();
        $('#plus-odin a.close').click(function() {
            $('#plus-odin').hide();
         });

         //$('#golos-ok').show();
        $('#golos-ok a.close').click(function() {
            $('#golos-ok').hide();
         });

         //$('#golos-fail').show();
        $('#golos-fail a.close').click(function() {
            $('#golos-fail').hide();
         });

         //окно с ошибкой при восстановлении кода
         $('#vosstanovlenie-error a.close').click(function() {
            $('#vosstanovlenie-error').hide();
            $('#error-message-text').text();
         });

         //toggle на "хочу сменить автомобиль"
         if ($('input.hochu_smenit_toogle').attr('checked')=='checked'){
             $('.radios.toggled, .info-field.toggled').toggle();
         }

         $('input.hochu_smenit_toogle').click(function(){
             $('.radios.toggled, .info-field.toggled').toggle();
         })

         //активность кнопки "далее" в предрегистрации
         $('#sogl_checkbox').click(nextActivity)

         //раскрашиваем таблицу приглашенных
         $('.invite-friends tr:odd').addClass('odd');

         //форма "пригласите друга по e-mail"
         $('#friend-email-inviting').ajaxForm({
            dataType: 'json',
            success: function(data, status) {
                //$('.invites-b').hide();
                $('.invites-a').show();
                $('#invite-sended').show();
            },
            error: function(XHR) {
                alert('Не удалось, попробуйте позже!');
                //$('#invite-sended').show();
            }

        });

        //голосование за собственную фотку
        $('#profile-registered a.up'). click(function(){
            var oThis = $(this);
            $('#plus-odin').show();
            $.each($('#plus-odin .container a'), function(){
                $(this).attr('href', $(this).attr('href')+oThis.parent().attr('photo_id'));
            })

//            var votes_count = 0;
//            oThis.html('<i></i>голос учтен<span>' + votes_count + '</span>');
//            oThis.addClass('dislike');
	    return false;
        });

        //активность кнопки "готово" в /profile/registered/activate-photo/
         $('#activate-sogl').click(function(){
             if ($('#activate-sogl').attr('checked')=='checked'){
                 $('#make-photo-form-button').removeClass('gray-disable');
             }else $('#make-photo-form-button').addClass('gray-disable');
         })

         //ограничение количества символов в comment
         if ($("#photo-slogan textarea").length)
            $("#photo-slogan textarea").maxlength();

         //welcome-screen
         $('#welcome-screen a.close').click(function() {
            $('#welcome-screen').hide();
            changeFrameHeight();
         });
         $('#show-advices').click(function(){
             $('#welcome-screen').show();
             changeFrameHeight();
             if ($.cookie("show_rules")=="0"&&($('#no-advices-please').attr('checked')==''||$('#no-advices-please').attr('checked')==undefined)){
                 $('#no-advices-please').attr('checked', 'checked');
             }
             return false;
         });
         $(document).not('#welcome-screen .container .jqTransformCheckboxWrapper, #welcome-screen .container .no-advices-please-label, #no-advices-please').click(function(){
            $('#welcome-screen').hide(); // клик был на странице вне элемента
            changeFrameHeight();
         });
         $('#welcome-screen .container .jqTransformCheckboxWrapper, #welcome-screen .container .no-advices-please-label, #no-advices-please').click(function(event){
             event.stopPropagation();
         })

         //куки-показываем правила
         if ($.cookie("show_rules")==null){    //если самый первый заход в ЛК
             $.cookie("show_rules", "1", {     //устанавливаем куки "показывать правила"
                  expires: 30,
                  path: "/"
             });
             $.cookie("show_rules_first_time", "1", {     //устанавливаем куки "показывать правила в первый заход сессии"
                  path: "/"
             });
         }
         if ($.cookie("show_rules_first_time")==null&&$.cookie("show_rules")=='1'){    //если началась новая сессия и установлено "показывать правила"
             $.cookie("show_rules_first_time", "1", {     //устанавливаем куки "показывать правила в первый заход сессии"
                  path: "/"
             });
         }

         //если установлены куки "показывать правила" и "показывать правила в первый заход сессии"
         if ($.cookie("show_rules")=='1'&&$.cookie("show_rules_first_time")=='1'){
             if ($('#welcome-screen').length){
                 $('#welcome-screen').show();    //показываем советы
                 changeFrameHeight();
                 $.cookie("show_rules_first_time", "0", {     //устанавливаем куки "не показывать правила далее в сессии"
                      path: "/"
                 });
             }
         }

         $('#no-advices-please').click(function(){
             if ($('#no-advices-please').attr('checked')=='checked'){
                 //alert('НЕ Показываем правила');
                 $.cookie("show_rules", "0", {
                  expires: 30,
                  path: "/"
                });
             }else{
                //alert('Показываем правила');
                 $.cookie("show_rules", "1", {
                  expires: 30,
                  path: "/"
                });
             }
         })

         //пригласить больше друзей
         $('#invite-more-friends').click(function(){
             $('.invites-a').hide();
             $('.invites-b').show();
             return false;
         })

         //подсветка элементов списка при наведении
         $('.scrolled li').hover(function(){
            $(this).addClass('scrolled-li-hover');
         }, function(){
            $(this).removeClass('scrolled-li-hover');
         })

         //переключение пола
         $('#gender0').click(function(){
            $('.g0-label').show();
            $('.g1-label').hide();
         })
         $('#gender1').click(function(){
            $('.g1-label').show();
            $('.g0-label').hide();
         });

         //окно "ваш телефон уже зарегистрирован в системе"
         $('#phone-reg-error a.close').click(function() {
            $('#phone-reg-error').hide();
         });

         //окно "регистрация по приглашению"
         //$('#invite-popup').show();
         $('#invite-popup a.close').click(function() {
            $('#invite-popup').hide();
         });

         //окно "пригласительная ссылка больше не действует"
         //$('#invite-fail').show();
         $('#invite-fail a.close, .close-invite-fail').click(function() {
            $('#invite-fail').hide();
         });

         //окно "приглашение вашему другу отправлено"
         $('#invite-sended a.close').click(function() {
            $('#invite-sended').hide();
         });

         //окно "вам отправлена СМС"
         //$('#sms-sended-info').show();
         $('#sms-sended-info a.close').click(function() {
             //$('#getSmsCodeButton').show();
            $('#sms-sended-info').hide();
         });

         //просмотр видео победителя
         $("#cool-video-show").fancybox({
                    'titleShow': false,
            'padding': 5,
            'overlayOpacity': .7,
            'overlayColor': '#fff',
            'transitionIn': 'elastic',
	    'transitionOut': 'elastic',
                    'type'      : 'swf',
            'swf'       : {'wmode':'transparent','allowfullscreen':'true'}
        });

        //окно "ожидайте сообщений"
        $('#wait-message a.close').click(function() {
            $('#wait-message').hide();
         });

         //реакция на изменение даты рождения
         $('.dates-special:eq(0) select').change(function(){
            var dob = Date.parse($('select[name="dob-month"]').val()+'.'+$('select[name="dob-day"]').val()+'.'+$('select[name="dob-year"]').val());
            if (dob==null){
                var dl = 31;
                while (true){
                    if (dob==null){
                        dl--;
                        $('select[name="dob-day"]').val(dl);
                        dob = Date.parse($('select[name="dob-month"]').val()+'.'+$('select[name="dob-day"]').val()+'.'+$('select[name="dob-year"]').val());
                    }else{
                        break;
                    }
                }
            }
             if (dob.addYears(18) < Date.today()){
                //старше 18ти
                if ($('#error-18-years').length){
                    $('#error-18-years').addClass('hidden');
                }
                if ($('#registration-form').length){
                    $('#registration-form .orange-button').removeClass('gray-disable2');
                }
                $('#registration-form-submit').removeClass('gray-disable2');
             }else{
                //младше 18ти
                if ($('#error-18-years').length==0){
                    $('.dates-special:eq(0)').prepend('<p id="error-18-years" class="clearfix error-colored">Вам должно быть не менее 18 лет</p>');
                }else{
                    $('#error-18-years').removeClass('hidden');
                }
                if ($('#registration-form').length){
                    $('#registration-form .orange-button').addClass('gray-disable2');
                }
                $('#registration-form-submit').addClass('gray-disable2');
             }
         })

         //
         $('#registration-form .required').keyup(nextActivity);

         nextActivity();

         //карусель победителей
         jQuery('#winners-carousel').jcarousel({
            vertical: true,
            scroll: 1,
            wrap: 'circular'
        });

})

