var tarotaro = ( function( $ ) { return {
	'containerId' : 'taro-_taroContainer',

	'container' : function() {
		return $( '#' + this.containerId );
	},

	'makeQS' : function() {
		var s = '';
		for( var i = 0; i < arguments.length; i++ ) {
			var o = arguments[i];
			for( var k in o )
				s += encodeURIComponent( k || '' ) + '=' + encodeURIComponent( o[k] || '' ) + '&';
		}
		return s.replace( /&$/, '' );		
	},

	'parseQS' : function( qs ) {
		var r = {};
		qs = qs.split( '&' );
		
		for( var i = 0; i < qs.length; i++ ) {
			var kv = qs[i].split( '=', 2 );
			r[ decodeURIComponent( kv[0] ) ] = decodeURIComponent( kv[1] );
		}

		return r;
	},

	'_requestId' : 0,
	'_callbacks' : {},
	'_cancels' : {},

	'cancel' : function( ri ) {
		var cancel = this._cancels[ri];

		if( typeof cancel == 'function' )
			cancel();
	},

	'appendElement' : function( el ) {
		if( document.getElementsByTagName('head').length )
			document.getElementsByTagName('head')[0].appendChild( el );
		else
			document.appendChild( el );
	},

	'evalResponseData' : function( data ) {
		if( typeof data == 'function' ) {
			return data.call( this );
		} else if( typeof data == 'object' ) {
			if( typeof data.init == 'function' )
				return data.init( this );
		}
	},

	'request' : function( args, cb ) {
		var _this = this;
		var ri = this._requestId++;
		var qs = this.makeQS( args, {
			'site_id' : this.siteId,
			'_' : Math.random(),
			'_callback' : 'tarotaro._callbacks[' + ri + ']'		
		} );

		var uri = this.uri;
		uri += ( uri.match( /\?/ ) ? '&' : '?' ) + qs;

		var sc = document.createElement('script');
		sc.type = 'text/javascript';
		sc.charset = 'utf-8';
		sc.src = uri;

		sc.onerror = sc.onload = sc.onreadystatechange = function() {
			if( !this.loaded && (!this.readyState || this.readyState == 'loaded' || this.readyState == 'complete') ){
				this.loaded = 1;
				this.onerror = this.onload = this.onreadystatechange = null;
				this.parentNode.removeChild(this);
				delete sc;
			}
		};

		this._cancels[ri] = function() {
			_this._callbacks[ri] = function() {
				_this.showWait( false );
				delete _this._callbacks[ri];
			};
			delete _this._cancels[ri];
		};

		this._callbacks[ri] = function( data ) {
			delete _this._callbacks[ri];
			delete _this._cancels[ri];

			_this.showWait( false );

			var r = _this.evalResponseData( data );

			if( r !== false && typeof cb == 'function' )
				cb.apply( _this, arguments );
		};

		this.appendElement( sc );
		return ri;
	},

	'_loadedCSS' : [],

	'addCSS' : function( uri ) {
		var el = document.createElement( 'link' );
		el.rel = 'stylesheet';
		el.type = 'text/css';
		el.media = 'screen';
		el.href = this.host + uri;

		this.appendElement( el );
		return el;
	},

	'loadCSS' : function( uri, keep ) {
		var el;
		var loaded = this._loadedCSS;

		if( !keep ) {
			while( loaded.length > 0 ) {
				el = loaded.pop();
				el.parentNode.removeChild( el );
			}
		}

		loaded.push( this.addCSS( uri ) );
	},

	'oa' : function(a) {
		var r = {};
		for( var i = 0; i < a.length; i++ ) {
			var obj = a[i];

			if( typeof( obj ) != 'object' )
				continue;

			for( var k in obj )
				r[k] = obj[k];
		}
		return r;
	},

	'o' : function() {
		return this.oa( arguments );
	},

	'parseLocationHash' : function() {
		return this.parseQS( window.location.hash.replace( /^#/, '' ) );
	},
	'setLocationHash' : function( h ) {
		window.location.hash = this.makeQS( h );
	},

	'initCommonElements' :  function() {
		var c = this.container();
		if( $.browser.msie && $.browser.version < 7 ) {
			c.find('#taro-floatmenu-container').hover( function() {
				$(this).css( 'overflow', 'visible' );
			}, function() {
				$(this).css( 'overflow', 'hidden' );
			} );
		}
	},

	'content' : function() {
		var el = document.getElementById( this.containerId );
		if( el ) {
			if( this.paymentInterval ) {
				clearInterval( this.paymentInterval );
				this.paymentInterval = null;
			}

			el.innerHTML = arguments[0];
			this.initCommonElements();
		}
	},

	'serializeForm' : function( formSel ) {
		var r = {};
		var a = $( formSel ).serializeArray();
		for( var i = 0; i < a.length; i++ ) {
			r[a[i].name] = a[i].value || '';
		}
		return r;
	},
	
	// возвращаем список имен инпутов с их значениями
	'serialize' : function() {
		var h = {};
		for( var i = 0; i < arguments.length; i++ ) {
			var s = $( arguments[i] );
			var to_h = false;
			switch(s.attr('type')){
				case 'checkbox':
					if (s.is(':checked')){
						to_h = true;
					};
					break;
				default:
					if( s.length ){
						to_h = true;
					};
			};
			if (to_h){
				h[ s.attr( 'name' ) ] = s.val();
			};
			
			
		}
		return h;
	},

	'_cachedRequests' : {},

	'cachedRequest' : function( id, args, cb ) {
		var data = this._cachedRequests[ id ];

		if( data ) {
			this.evalResponseData( data );

			if( typeof cb == 'function' )
				cb.call( this, data );
			return 0;
		} else {
			this.showWait( true );

			return this.request(
				args,
				function( data ) {
					if( typeof cb == 'function' )
						cb.call( this, data );

					this._cachedRequests[ id ] = data;		
				} );
		}
	},

	'update' : function() {
		this.request( this.oa( arguments ) );
		return false;
	},

	'startPage' : function( args, id ) {
		args = this.o( { 'action' : 'start' }, args );
		id = id || args['spread'] || '';

		this.cachedRequest( id, args );
		return false;
	},

	'showComments' : function( spread ) {
		this.scrollTo('#taro-floatmenu-container');
		return this.update( { 'spread' : spread, 'action' : 'comments-view' } );
	},
	
	'showRegions' : function( spread, country_id ) {
		jQuery('.region_ajax').remove();
		jQuery('.city_ajax').remove();
		return this.update( { 'spread' : spread, 'action' : 'regions', 'country_id' : country_id } );
	},
	
	'showCitys' : function( spread, region_id ) {
		jQuery('.city_ajax').remove();
		return this.update( { 'spread' : spread, 'action' : 'citys', 'region_id' : region_id } );
	},
	
	'showProducer' : function( spread, admin_id ) {
		this.scrollTo('#taro-floatmenu-container');
		return this.update( { 'spread' : spread, 'action' : 'producer-descr', 'admin_id' : admin_id } );
	},

	'showSpread' : function( spread, args ) {
		if( spread )
			args = this.o( { 'spread' : spread }, args );

		this.cachedRequest(
			spread || '',
			this.o( args, { 'action' : 'start' } ),
			function() {
				this.setLocationHash( args );
			} );
		
		this.scrollTo('#taro-floatmenu-container');
		
		return false;
	},
	
	'showDailySpread' : function( date ) {
		var args = { 'spread' : 'taroday', 'date' : date };
		var nargs = $.extend({}, args, {'action': 'start'} );

		this.cachedRequest(
			'daily-' + ( date || '' ),
			nargs,
			function() {
				this.setLocationHash( args );
			} );

		return false;
	},

	'showExample' : function( spread, args ) {
		args = this.o( { 'spread' : spread }, args, { 'action' : 'example' } );

		this.cachedRequest(
			'example-' + ( spread || '' ),
			args,
			function() {
				this.setLocationHash( args );
			} );

		return false;
	},

	'checkName' : function( name ) {
		return /\S/.test( name ) && name.replace( /\s/g, '' ).length;
	},

	'checkEmail' : function( email ) {
		return /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,10}$/.test( email );
	},

	'scrollTo' : function( sel ) {
		window.scrollTo(0, parseInt( this.container().find( sel ).offset().top) - 20);
	},

	'initCommentsForm' : function( spread ) {
		var t = this;
		var form = $( '#taro-comments-form', this.container() );
		form.submit( function() {
			t.update(
				{ 'spread' : spread, 'action' : 'comment' },
				t.serializeForm( form )
			);
			return false;
		} );
		
		var copyFrom = $('#comments-form-copy');
		if( copyFrom ) {
			$('#comments-city').attr( 'value', $('#comments-copy-city').attr('value') );
			$('#comments-age').attr( 'value', $('#comments-copy-age').attr('value') );
			$('#comments-body').attr( 'value', $('#comments-copy-body').attr('value') );
		}
	},
	
	'initSubmitForm' : function( state, formSel, submitSel, inputs, validate ) {
		var t = this;

		var onsubmit = function() {
			if( !state.done ) {
				alert( "Вы не выбрали нужное количество карт" );
				return false;
			}

			var fields = inputs ? t.serialize.apply( t, inputs ) : {};

			if( typeof validate == 'function' ) {
				if( validate.call( t, fields ) === false )
					return false;
			}

			t.showWait( true );
			t.update( { 'spread' : state.spread, 'action' : 'submit', 'picked_state' : state.picked, 'spreadrubrucId' : state.spread_rubruc_Id }, fields );
			return false;
		};

		$( formSel ).submit( onsubmit );

		if( submitSel ) {
			$( submitSel ).click( function() {
				onsubmit();
				return false;
			} );
		}
	},

	'invalidBonusCode' : function() {
		alert( "Неверный промо-код" );
	},

	'initBonusForm' : function( state, formSel, inputs, validate ) {
		var t = this;
		var onsubmit = function() {
			var fields = inputs ? t.serialize.apply( t, inputs ) : {};

			if( typeof validate == 'function' ) {
				if( validate.call( t, fields ) === false )
					return false;
			}

			t.showWait( true );
			t.update( { 'oid' : state.oid, 'action' : 'promo-code' }, fields );
			return false;
		};

		$( formSel ).submit( onsubmit );
	},

	'initCardsPick' : function( state, sel, cb, extra ) {
		var t = this;

		state.done   = false;
		state.picked = '';
		state.count  = 1;
		
		var onclick = function() {
			var el = this;

			if( state.done ) {
				$(sel).unbind( 'click', onclick );
				$(sel).click( function() { t.message( "Вы уже выбрали необходимое количество карт" ); return false; } );
				return false;
			};

			t.request(
				t.o( { 'spread' : state.spread, 'action' : 'pick', 'picked_state' : state.picked }, extra ),
				function( data ) {
					if( state.count != data.count )
						return;

					state.picked = data.picked_state || '';
					state.count++;

					if( typeof cb == 'function' )
						cb.call( t, el, data );

					if( data.is_last ) {
						state.done = true;
						$(sel).unbind( 'click', onclick );
						$(sel).click( function() { t.message( "Вы уже выбрали необходимое количество карт" ); return false; } );
					}
				} );

			return false;
		};

		$(sel).click( onclick );
	},

	'message' : function() {
		alert.apply( window, arguments );
	},

	'reset' : function() {
		window.location.reload();
	},

	'showWaitTimeout' : null,

	'showWait' : function( show ) {
		if( this.showWaitTimeout )
			clearTimeout( this.showWaitTimeout );

		this.showWaitTimeout = null;

		var s1 = '#' +  this.containerId;
		var s2 = '#' +  this.containerId + '-wait';
		var counter = $('#taro-main_counter');

		if( !show ) {
			$(s2).hide();
			$(s1).show();
			counter.show();
			return;
		}

		this.showWaitTimeout = setTimeout( function() {
			counter.hide();
			$(s1).hide();
			$(s2).show();
		}, 4 * 1000 );
	},

	'showDiv': function( nodeId ) {
		var node = document.getElementById( nodeId );
		if( node ) node.style.display = '';
		var taroBg = document.getElementById( 'taro-popup-bg' );
		if( taroBg ) taroBg.style.display = '';
		this.scrollTo('#taro-floatmenu-container');
		return false;
	},

	'hideDiv': function( nodeId ) {
		var node = document.getElementById( nodeId );
		if( node ) node.style.display = 'none';
		var taroBg = document.getElementById( 'taro-popup-bg' );
		if( taroBg ) taroBg.style.display = 'none';
		return false;
	},
	
	// Обработка чекбоксов подписок WMJ
	'initWMJ': function( wmj_checkboxId ){
		var wmj_checkbox = $(wmj_checkboxId);
		var wmj_checkboxes_d = $('.taro-wmj-d');
		
		wmj_checkboxes_d.click(function() {
			if( wmj_checkboxes_d.filter(':checked').size() > 0 ) {
				wmj_checkbox.attr('checked', true);
			} else {
				wmj_checkbox.attr('checked', false);
			}
			return true;
		});
		
		wmj_checkbox.click(function(){
			if( $(this).attr('checked') ) {
				wmj_checkboxes_d.attr('checked', true);
			} else {
				wmj_checkboxes_d.attr('checked', false);
			}
			return true;
		});
	},
	
	'event_sel_co': function( element ){
		var taro_country = $(element);
		var taro_country_val = taro_country.val();

		$('.taro-operator').hide();
		$('#taro-country-' + taro_country_val  + '-operators' ).show().change();
		$('#taro-country-prices-' + taro_country_val ).siblings().hide().end().show();
		$('#taro-sms-message').text(taro_country.find(':selected').attr('message'));
		
		return true;
	},
	
	'writeCode' : function() {
		document.write( '<div id="' + this.containerId + '"></div>' );
		document.write(
			'<div style="position: absolute; font: 16px/1 Arial, sans-serif; left: 30px; top: 30px; color: #000;" id="' + this.containerId + '-wait">' +
				'<img src="' + this.host + '/i/load.gif" style="float: left; margin: 2px 10px 0 0;" alt="" /> Подождите, идет загрузка...' +
			'</div>'
		);

		this.addCSS( '/s/rasklad/popup.css' );
	},

	'start' : function( options ) {
		this.containerId = options['containerId'] || this.containerId;
		this.host = options['host'] || 'http://tarotaro.ru';
		this.siteId = options['sid'] || options['siteId'];
		this.spreadrubrucId = options['spreadrubrucId'];
		this.uri = this.host + '/spreads/';

		this.writeCode();

		var t = this;
		$( function() {
			var h = t.parseLocationHash();
			if( h['spread'] ) {
				if( h['action'] == 'example' ) {
					t.showExample( h['spread'], {spreadrubrucId : options['spreadrubrucId']} );
				}
				else {
					h['spreadrubrucId'] = options['spreadrubrucId'];
					t.startPage( h );
				}
			} else if( h['oid'] ) {
				if( h['action'] == 'admin_preview' ) {
					t.update( h );
				} else {
					t.update( { 'oid' : h['oid'], spreadrubrucId : options['spreadrubrucId'] } );
				}
			} else if( options['spread'] ) {
				t.startPage( { 'spread' : options['spread'] } );
			} else {
				t.startPage( { 'spreadrubrucId' : options['spreadrubrucId'] } );
			}
		});
	},

   '_loadedScripts' : {},

   'loadScript' : function( path, cb ) {
       if( this._loadedScripts[path] ) {
           if( typeof cb == 'function' )
               cb();
           return;
       }

       var sc = document.createElement('script');
       sc.type = 'text/javascript';
       sc.charset = 'utf-8';
       sc.src = this.host + path;

       sc.onerror = sc.onload = sc.onreadystatechange = function() {
           if( !this.loaded && (!this.readyState || this.readyState == 'loaded' || this.readyState == 'complete') ){
               this.loaded = 1;
               this.onerror = this.onload = this.onreadystatechange = null;

               if( typeof cb == 'function' )
                   cb();
           }
       };

       this.appendElement( sc );
       this._loadedScripts[path] = true;
   }
   
} } )( jQuery.noConflict() );

function citys(id_region){

	jQuery('.city_ajax').remove();

	jQuery.get('http://tarotaro.ru/city/'+id_region+'/',function(text){
		if( text ) {
			var citys=text.split(";");
			for (var i=1;i<citys.length;i+=1){
				var id = citys[i];
				var name = citys[++i];
				jQuery('<option class="city_ajax">'+name+'</option>')
					.attr({value: id})
					.appendTo('.citys_ajax');
			}
		}
	});
}

function regions(id_country){

	jQuery('.region_ajax').remove();

	jQuery.get('http://tarotaro.ru/region/'+id_country+'/',function(text){
		if( text ) {
			var regions=text.split(";");
			for (var i=1;i<regions.length;i+=1){
				if (i == 1){
					citys(regions[i])
				}
				var id = regions[i];
				var name = regions[++i];
				jQuery('<option class="region_ajax">'+name+'</option>')
					.attr({value: id})
					.appendTo('.regions_ajax');
			}
		}
	});
}
var taro_months = ['января', 'февраля', 'марта', 'апреля', 'июня', 'июля', 'августа', 'сентября', 'октября', 'ноября', 'декабря'];
var taro_dd, taro_md, taro_xd, taro_defaultDate, taro_minDate, taro_maxDate;
function taro_datepickerSetLinks( cd ){
			var td = '';
			if ( cd > taro_md){
					var dayBefore = new Date( cd.getTime() - 86400000 );
					dayBefore = dayBefore.getDate() + ' ' + taro_months[dayBefore.getMonth()-1] + ' ' + dayBefore.getFullYear();
					td += '<a href="javascript:void(0)" onclick="taro_datepickerChangeCD(\'-1\')">&lt;&lt;Предыдущий день, ' + dayBefore + '</a><br>';
			} else {
					td += '<br />';
			}
			if ( cd < taro_xd){
					var dayAfter = new Date( cd.getTime() + 86400000 );
					dayAfter = dayAfter.getDate() + ' ' + taro_months[dayAfter.getMonth()-1] + ' ' + dayAfter.getFullYear();
					td += '<a href="javascript:void(0)" onclick="taro_datepickerChangeCD(\'1\')">Следующий день, ' + dayAfter + ' &gt;&gt;</a>';
			} else {
					td += '<br />';
			}
			var maindate = new Date( taro_dd ) ;
			maindate = maindate.getDate() + ' ' + taro_months[maindate.getMonth()-1] + ' ' + maindate.getFullYear();
			var md_formatted = new Date( taro_md );
			md_formatted = md_formatted.getDate() + ' ' + taro_months[md_formatted.getMonth()-1] + ' ' + md_formatted.getFullYear();
			var xd_formatted = new Date( taro_xd );
			xd_formatted = xd_formatted.getDate() + ' ' + taro_months[xd_formatted.getMonth()-1] + ' ' + xd_formatted.getFullYear();

			jQuery('.taro-i-block2')
					.html('<a class="taro-i-back" href="javascript:void(0)" onclick="taro_datepickerChangeCD(\'' + taro_defaultDate + '\')">&lt;&lt; Главная, ' +  maindate + '</a><div class="taro-i-days">' + td +'</div>');
			jQuery('.taro-i-dates-links')
					.html('<strong><a href="javascript:void(0)" onclick="taro_datepickerChangeCD(\'' + taro_minDate + '\')">' + md_formatted + '</a> - <a href="javascript:void(0)" onclick="taro_datepickerChangeCD(\'' + taro_maxDate + '\')">' + xd_formatted + '</a></strong>');
			jQuery('.interpretations').hide();
			jQuery('.interpretations[date=' + ((cd.getDate()<10)?"0"+cd.getDate():cd.getDate()) +'-'+ ( (cd.getMonth()<10)?"0"+(cd.getMonth()+1):(cd.getMonth()+1) )+'-'+ (cd.getFullYear()) + ']').show();
};

function taro_datepickerChangeCD( new_cd ){
		
		if ( new_cd <= 1){
				new_cd = new Date (jQuery( "#datepicker" ).datepicker( "getDate" ).getTime() + 86400000 * new_cd);
				new_cd = ((new_cd.getDate()<10)?"0"+new_cd.getDate():new_cd.getDate()) +'-'+ ( (new_cd.getMonth()<10)?"0"+(new_cd.getMonth()+1):(new_cd.getMonth()+1) )+'-'+ (new_cd.getFullYear());
		}
		jQuery( "#datepicker" ).datepicker( "setDate", new_cd );
		taro_datepickerSetLinks(  new Date( new_cd.substr(6,4) , new_cd.substr(3,2) - 1, new_cd.substr(0,2) )  );
}


