//	Version: 1.0.0
//	Last update: 2012-01-18

$(document).ready(function() {

	$('.b-plot').tooltipPlan();
//	$('.anchorLink').anchorAnimate();

	$('.link-print').click(function () {
		var regex = $(this).attr('href').match(/\/([a-zA-Z0-9-_.]+)\./);

		var winprint = window.open("/images/"+regex[1]+".html", "myWindow");
		return false;
	});

	$('.plan-link-print').click(function () {
		var regex = $(this).attr('href').match(/\/([a-zA-Z0-9-_.]+)\./);

		var winprint = window.open("/images/"+regex[1]+".php", "myWindow");
		return false;
	});

	$('.b-plot').not('.reserve, .sold').fixedBox({ajax:'/includes/handlers/ajax.php'});
//	$('#request-db').fixedBox2({ajax:'/includes/handlers/ajax_zayavka.php?ajax', aSend:{action:'form_db'}});

/*	var form = null;
	$('.js-form-order').ajaxForm({
		dataType: "json",
		beforeSubmit: function(arr, $form, options) {
			form = $form;
			$('.send_order').attr('disabled', 'disabled');
		},
		success: function(data) {
			showAjaxMsg(data);

			$('.send_order').attr('disabled', '');
		}
	});
*/
	$('form.ajaxform').live('submit', function() {
		var formname = $(this).attr('name');
		var poselok = $(this).context.poselok.value;

		$(this).ajaxSubmit({ dataType:'json',
			beforeSubmit: function(arr, $form, options) {
				showMsg('', 'loading');
				msg.timec = (new Date().getTime())+500;
			},
			success: function(data) {
				if (formname=='form-order' && data.type_msg==='ok') {
//					yaCounter1747021.reachGoal('ORDER', poselok);
				}
				showAjaxMsg(data);
				if (msg.timec > (new Date()).getTime()) {
					$('#js-submit').everyTime("200ms", 'msgTimer2', function() {
						if (msg.timec < (new Date()).getTime()) {
							$(this).html('Отправить заявка');
							$(this).stopTime('msgTimer2');
						}
					});
				}
				else
					$('#js-submit').html('Отправить заявку');
			}
		});
		return false; // <-- important!
	});

	$('form.ajaxform').ajaxError(function(e, jqxhr, settings) {
		showMsg('ajaxError (Ошибка в полученных данных):<br>'+jqxhr.responseText, 'error');
	});

/*	$('#ff-fio, #ff-phone').click(function() {
		checkFormOrder();
	});

	$('#ff-fio, #ff-phone').keypress(function() {
		checkFormOrder();
	});
	function checkFormOrder() {
		if ($('#ff-fio').val() && $('#ff-phone').val())
			$('#js-order-submit').removeAttr('disabled');
		else
			$('#js-order-submit').attr('disabled', 'disabled');
	}
*/
});

var msg = new Object();
msg.timec = new Date();
msg.type_last = '';

function showAjaxMsg(data) {
	if (data.type_msg) {
		switch (data.type_msg) {
			case 'error':
				showMsg(data.error, 'error');
			break;

			case 'ok':
				showMsg(data.ok, 'ok');
				if (data.reload!==undefined) {
	//			alert(data.reload+' '+typeof(data.reload));
					if (data.reload===true) {
						$('#js-msgbox').before('<div id="ui-background" class="ui-widget-overlay" style="z-index:'+$('#js-msgbox').css('z-index')+'"><div>Перезагрузка страницы...</div></div>');
						setTimeout('location.replace("")', 800);
					}
					else if (typeof(data.reload)==='string') {
						$('#js-msgbox').before('<div id="ui-background" class="ui-widget-overlay" style="z-index:'+$('#js-msgbox').css('z-index')+'"><div>Перезагрузка страницы...</div></div>');
						setTimeout('location.replace("'+data.reload+'")', 800);
					}
				}
			break;

			case 'info':
				showMsg(data.info, 'info');
			break;

			case 'warning':
				showMsg(data.warning, 'warning');
			break;
		}
	}
	else
		showMsg('Нет ответа от сервера', 'warning');
	msg.type_last = data.type_msg;
}

function showMsg(data, type) {
	var text = '';
	var msgbox = $('#js-msgbox');

	msgbox.addClass('b-msg_'+type);
	if (type !== msg.type_last)
		msgbox.removeClass('b-msg_'+msg.type_last);
	
	if (type=='loading') {
		$('#js-submit').html('Отправка заявки...');

//		msgbox.before('<div id="ui-background" class="ui-widget-overlay" style="z-index:'+msgbox.css('z-index')+'"><div>Загрузка...</div></div>');
	}
	else {
		if (typeof(data)=="object") {
			if (data.length==1)
				text = data[0];
			else {
				for (i=0; i<data.length; i++) {
					text += '<li>'+data[i]+'</li>';
				}
				text = '<ul>'+text+'</ul>';
			}
		}
		else
			text = data;

		$('#js-msgbox__text').html(text);

		msgbox.slideDown();
		msgbox.stopTime('msgTimer');
		if (type=='ok' || type=='info') {
			msgbox.oneTime("7s", 'msgTimer', function() {
				msgbox.slideUp();
			});
		}
		else if (type=='warning') {
			msgbox.oneTime("10s", 'msgTimer', function() {
				msgbox.slideUp();
			});
		}
		else {
			msgbox.oneTime("30s", 'msgTimer', function() {
				msgbox.slideUp();
			});
		}
	}
};

(function($) {
/***
 *	Anchor
 **/
jQuery.fn.anchorAnimate = function(settings) {

	settings = jQuery.extend({
		speed : 1000
	}, settings);	
	
	return this.each(function(){
		var caller = this
		$(caller).click(function (event) {	
			event.preventDefault()
			var locationHref = window.location.href
			var elementClick = $(caller).attr("href")
			
			var destination = $(elementClick).offset().top;
			$("html:not(:animated),body:not(:animated)").animate({ scrollTop: destination}, settings.speed, function() {
//					window.location.hash = elementClick;
			});
			return false;
		})
	})
};

jQuery.fn.tooltipPlan = function(options) {
	 var defaults = {  
		offsetX: 15,  //X Offset value
		offsetY: 10,  //Y Offset value
		fadeIn : 'fast', //Tooltip fadeIn speed, can use, slow, fast, number
		fadeOut : 'fast',//Tooltip fadeOut speed, can use, slow, fast, number
		ajax: false,
		parentID: 'planMap-',
		dataAttr : 'data',	//Used when we create seprate div to hold your tooltip data, so plugin search div tage by using id 'data' and current href id on whome the mouse pointer is so if your href id is '_tooltip_1' then the div which hold that tooltips content should have id 'data_tooltip_1', if you change dataAttr from default then you need to build div tag with id 'current dataAttr _tooltip_1' without space
		bordercolor: '#6CE26C', // tooltip border color
		bgcolor: '#F8F8F8', //Tooltip background color
		fontcolor : '#006699', //Tooltip Font color
		fontsize : '15px', // Tooltip font size
		folderurl : 'NULL', // Folder url, where the tooltip's content file is placed, needed with forward slash in the last (/), or can be use as http://www.youwebsitename.com/foldername/ also.
		filetype: 'txt', // tooltip's content files type, can be use html, txt
		height: 'auto', // Tooltip's width
		width : 'auto' //Tooltip's Height
	   };  
	var options = $.extend(defaults, options);
	//Runtime div building to hold tooltip data, and make it hidden
	var $tooltip = $('<div id="divToolTipPlan"></div>');
	return this.each(function(){					
		$('body').append($tooltip);
		$tooltip.hide();

		//	Runtime variable definations
		var element = this;
		var id = $(element).attr('id');
		var filename = options.folderurl + id + '.' + options.filetype;
		var dialog_id = '#divToolTipPlan';

		//	Tooltips main function
		$(this).hover(function(e) {
			//var size = "Windows Width : " + $(document).width() + " Tip Width : " + e.pageX + "\n" + "Windows Height : " + $(document).height() + " Tip Height : " + e.pageY;
			//alert(size);
			//to check whether the tooltips content files folder is defined or not
			if (options.folderurl != "NULL") {
				$(dialog_id).load(filename);
			}
			else {
				if (options.ajax) {
/*					var parent = $(this).parent().attr("id");
					parent = parent.replace(options.parentID, '');
					var id = $(this).text();

					$.getJSON('/includes/handlers/poselok.php?id='+id, function(data) {
						var data_html = "";

						data_html += '<p><b>№ участка:</b> '+data.id+'</p>';
						data_html += '<p><b>Площадь:</b> '+data.sotki+' соток</p>';

						if (data.state==2) {
							data_html += '<p><b>Участок продан</b></p>';
						}
						else if (data.state==1) {
							data_html += '<p><b>Участок зарезервирован</b></p>';
						}
						else {
							data_html += '<p><b>Цена участка, при оплате:</b></p>';
							data_html += '<p><b>-> 100% (-5%):</b> '+data.cena_100+' руб.</p>';
							data_html += '<p><b>-> 40+40+20 (номинал):</b> '+data.cena_40_40_20+' руб.</p>';
							data_html += '<p><b>-> 50+50 (+33,33%):</b> '+data.cena_50_50+' руб.</p>';
							data_html += '<p><b>-> 30+70 (+66,67%):</b> '+data.cena_30_70+' руб.</p>';
						}
				//			data_html += '<p><a href="/index.php?menu=2&submenu=4">Подробнее про варианты оплаты</a></p>';	
						$(dialog_id).html(data_html);
//						console.log($(this).css('left'));

						$('#js-tooltip').html(data_html);
						$('#js-tooltip').css({left:0, top:0}).show();
					});
*/
				}
				else {
					var id = $(this).text().replace(/\//g, '_');
					$(dialog_id).html($('#plot'+id).html());
				}
			}

			//assign css value to div
			if ($(document).width() / 2 < e.pageX) {
				$(dialog_id).css({
					'top' : e.pageY + options.offsetY,
					'left' :  e.pageX - $(dialog_id).width() + options.offsetX,
					'height' : options.height,
					'width' : options.width
				});
				//alert(size);
			} else {	
				$(dialog_id).css({
					'top' : e.pageY + options.offsetY,
					'left' : e.pageX + options.offsetX,
					'height' : options.height,
					'width' : options.width
				});
			}

			$(dialog_id).stop(true, true).show();
		}, function() {
			// when mouse out remove all data from div and make it hidden
			$(dialog_id).stop(true, true).hide().html('<img src="/themes/site/images/loader.gif" class="loader" />');
		}).mousemove(function(e){	
			// to make tooltip moveable with mouse	
			if($(document).width() / 2 < e.pageX){		
			$(dialog_id).css({
				'top' : e.pageY + options.offsetY,
				'left' : e.pageX - $(dialog_id).width(),
				'height' : options.height,
				'width' : options.width
				});
			//$(dialog_id).html(e.pageX - $(dialog_id).width());
			} else {
				$(dialog_id).css({
				'top' : e.pageY + options.offsetY,
				'left' : e.pageX + options.offsetX,
				'height' : options.height,
				'width' : options.width
				});
			}
		});
	});
};
})(jQuery);
 

jQuery.fn.extend({
	everyTime: function(interval, label, fn, times, belay) {
		return this.each(function() {
			jQuery.timer.add(this, interval, label, fn, times, belay);
		});
	},
	oneTime: function(interval, label, fn) {
		return this.each(function() {
			jQuery.timer.add(this, interval, label, fn, 1);
		});
	},
	stopTime: function(label, fn) {
		return this.each(function() {
			jQuery.timer.remove(this, label, fn);
		});
	}
});

jQuery.extend({
	timer: {
		guid: 1,
		global: {},
		regex: /^([0-9]+)\s*(.*s)?$/,
		powers: {
			// Yeah this is major overkill...
			'ms': 1,
			'cs': 10,
			'ds': 100,
			's': 1000,
			'das': 10000,
			'hs': 100000,
			'ks': 1000000
		},
		timeParse: function(value) {
			if (value == undefined || value == null)
				return null;
			var result = this.regex.exec(jQuery.trim(value.toString()));
			if (result[2]) {
				var num = parseInt(result[1], 10);
				var mult = this.powers[result[2]] || 1;
				return num * mult;
			} else {
				return value;
			}
		},
		add: function(element, interval, label, fn, times, belay) {
			var counter = 0;
			
			if (jQuery.isFunction(label)) {
				if (!times) 
					times = fn;
				fn = label;
				label = interval;
			}
			
			interval = jQuery.timer.timeParse(interval);

			if (typeof interval != 'number' || isNaN(interval) || interval <= 0)
				return;

			if (times && times.constructor != Number) {
				belay = !!times;
				times = 0;
			}
			
			times = times || 0;
			belay = belay || false;
			
			if (!element.$timers) 
				element.$timers = {};
			
			if (!element.$timers[label])
				element.$timers[label] = {};
			
			fn.$timerID = fn.$timerID || this.guid++;
			
			var handler = function() {
				if (belay && this.inProgress) 
					return;
				this.inProgress = true;
				if ((++counter > times && times !== 0) || fn.call(element, counter) === false)
					jQuery.timer.remove(element, label, fn);
				this.inProgress = false;
			};
			
			handler.$timerID = fn.$timerID;
			
			if (!element.$timers[label][fn.$timerID]) 
				element.$timers[label][fn.$timerID] = window.setInterval(handler,interval);
			
			if ( !this.global[label] )
				this.global[label] = [];
			this.global[label].push( element );
			
		},
		remove: function(element, label, fn) {
			var timers = element.$timers, ret;
			
			if ( timers ) {
				
				if (!label) {
					for ( label in timers )
						this.remove(element, label, fn);
				} else if ( timers[label] ) {
					if ( fn ) {
						if ( fn.$timerID ) {
							window.clearInterval(timers[label][fn.$timerID]);
							delete timers[label][fn.$timerID];
						}
					} else {
						for ( var fn in timers[label] ) {
							window.clearInterval(timers[label][fn]);
							delete timers[label][fn];
						}
					}
					
					for ( ret in timers[label] ) break;
					if ( !ret ) {
						ret = null;
						delete timers[label];
					}
				}
				
				for ( ret in timers ) break;
				if ( !ret ) 
					element.$timers = null;
			}
		}
	}
});

if (jQuery.browser.msie)
	jQuery(window).one("unload", function() {
		var global = jQuery.timer.global;
		for ( var label in global ) {
			var els = global[label], i = els.length;
			while ( --i )
				jQuery.timer.remove(els[i], label);
		}
	});


	
/***************************************************************************
 *  jQuery FixedBox Plugin
 *  @requires jQuery v1.3 or 1.4
 *  Version: 1.0
 */
(function($) {
	jQuery.fn.fixedBox = function(options){
		var defaults = {
			container: '#box-order',
			align: 'center',
			valign: 'center',
			fadeIn : 'normal', //Tooltip fadeIn speed, can use, slow, fast, number
			fadeOut : 'normal',//Tooltip fadeOut speed, can use, slow, fast, number
			margin_g: '30px',
			margin_v: '30px',
			height: 'auto',
			width : 'auto',
			ajax : '',
			ajaxData : ''
		};  

		var options = $.extend(defaults, options);

		$(this).click(function() {
//		alert($(this).attr('id'));
			var fixedbox_id = $(this).attr('id');
			if (options.container)
				var fixedbox = $(options.container);
			else
				var fixedbox = $('#fb-'+fixedbox_id);

			$('.backfixedbox').remove();
//			$('#js-order-submit').attr('disabled', 'disabled');

			if (options.ajax != '') {
				var parent = $(this).parent('.b-plan');
				var plot_id = $(this).html();

				$.post(options.ajax, {cmd:'get_plotdata', id:plot_id, poselok:parent.attr('id')},
					function(data) {
						if (fixedbox_id=='NULL' || fixedbox_id=='')
							fixedbox_id = 1;

						if (fixedbox.is('.fixedbox')) {
							$("#ff-sotki").val(data.obj.sotki);
							$("#ff-plot").val(plot_id);
						}
						else {
							$('body').append('<div id="fb-'+fixedbox_id+'" class="fixedbox">'+data.obj+'</div>');
							fixedbox = $('#fb-'+fixedbox_id);
							fixedbox.before('<div class="backfixedbox">&nbsp;</div>');
							$('.backfixedbox').fadeIn();
							$(fixedbox).fadeIn(options.fadeIn);
						}
					},
					'json'
				);
			}

			$(fixedbox).before('<div class="backfixedbox">&nbsp;</div>');
			
			if (options.height == 'auto') {
				var hw = $(window).height() - 2*30;
				
				if (($(fixedbox).height()-hw) > 0) {
					$(fixedbox).css({'top':options.margin_v, 'bottom':options.margin_v})
				}
			}

			if (options.align == 'center') {
				var w = fixedbox.width()/2;
				fixedbox.css({'margin-left':-w})
			}

			if (options.valign == 'center') {
				var h = fixedbox.height()/2;
				fixedbox.css({'margin-top':-h});
			}

			$('.backfixedbox').fadeIn();
			$(fixedbox).fadeIn(options.fadeIn);
		});
		
		$('.backfixedbox, .fixedbox-close').live('click', function() {
			$('.fixedbox').fadeOut(options.fadeOut);
			$('.backfixedbox').fadeOut();
			$('.backfixedbox').remove();
			$('.block_msg').hide();
		});

	};
})(jQuery);

/********************************************************************/
/**
 *  jQuery FixedBox Plugin
 *  @requires jQuery v1.3 or 1.4
 *
 *  Version: 1.0
 *  Dated : 10-Feb-2010
 *	24-Jan-2010 : V1.1 : Build tooltip without static file.
 */
(function($) {
	jQuery.fn.fixedBox2 = function(options){
		var defaults = {  
			align: 'center',
			fadeIn : 'normal', //Tooltip fadeIn speed, can use, slow, fast, number
			fadeOut : 'normal',//Tooltip fadeOut speed, can use, slow, fast, number
			margin_g: '30px',
			margin_v: '30px',
			height: 'auto',
			width : 'auto',
			cmd : '',
			fixedbox : '#fixedbox',
			ajax : '',
			aSend : new Object,
			sendID : false
		};  

		var options = $.extend(defaults, options);

		$(this).click(function() {

			$('.backfixedbox').remove();

			var id = $(this).attr('id');
			var box = '';

			if (options.fixedbox == '')
				box = $('#fixedbox-'+id);
			else
				box = options.fixedbox;

			$(box).before('<div class="backfixedbox">&nbsp;</div>');

			if (options.ajax != '') {
				var aSend = options.aSend;
				if (options.sendID)
					aSend.id = id;

				$.post(options.ajax, aSend, function(data){
					$(box).html(data);
				}, 'html');
			}

			if (options.height == 'auto') {
				var hw = $(window).height() - 2*30;

				if (($(box).height()-hw) > 0) {
					$(box).css({'top':options.margin_v, 'bottom':options.margin_v})
				}
				
/*				if (options.margin_v != 'auto') {
					$(box).css({'top':options.margin_v, 'bottom':options.margin_v})
				}*/
			}
			$('.backfixedbox').fadeIn();
			$(box).fadeIn(options.fadeIn);
		});
		
		if (options.cmd == 'close') {
			close();
		}

		$('.backfixedbox, .fixedbox-close').live('click', function() {
			close();
		});

		function close() {
			$('.fixedbox').fadeOut(options.fadeOut);
			$('.backfixedbox').fadeOut();
			$('.backfixedbox').remove();
		}

	};
})(jQuery);
