/* Copyright (c) 2007 Paul Bakaus (paul.bakaus@googlemail.com) and Brandon Aaron (brandon.aaron@gmail.com || http://brandonaaron.net)
 * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
 * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
 *
 * $LastChangedDate: 2007-09-29 01:08:25 +0100 (Sat, 29 Sep 2007) $
 * $Rev: 3493 $
 *
 * Version: @VERSION
 *
 * Requires: jQuery 1.2+
 */

(function($){
	
$.dimensions = {
	version: '@VERSION'
};

// Create innerHeight, innerWidth, outerHeight and outerWidth methods
$.each( [ 'Height', 'Width' ], function(i, name){
	
	// innerHeight and innerWidth
	$.fn[ 'inner' + name ] = function() {
		if (!this[0]) return;
		
		var torl = name == 'Height' ? 'Top'    : 'Left',  // top or left
		    borr = name == 'Height' ? 'Bottom' : 'Right'; // bottom or right

		return num(this, name.toLowerCase()) + num(this, 'padding' + torl) + num(this, 'padding' + borr);
	};
	
	// outerHeight and outerWidth
	$.fn[ 'outer' + name ] = function(options) {
		if (!this[0]) return;
		
		var torl = name == 'Height' ? 'Top'    : 'Left',  // top or left
		    borr = name == 'Height' ? 'Bottom' : 'Right'; // bottom or right
		
		options = $.extend({ margin: false }, options || {});
		
		return num(this, name.toLowerCase())
				+ num(this, 'border' + torl + 'Width') + num(this, 'border' + borr + 'Width')
				+ num(this, 'padding' + torl) + num(this, 'padding' + borr)
				+ (options.margin ? (num(this, 'margin' + torl) + num(this, 'margin' + borr)) : 0);
	};
});

// Create scrollLeft and scrollTop methods
$.each( ['Left', 'Top'], function(i, name) {
	$.fn[ 'scroll' + name ] = function(val) {
		if (!this[0]) return;
		
		return val != undefined ?
		
			// Set the scroll offset
			this.each(function() {
				this == window || this == document ?
					window.scrollTo( 
						name == 'Left' ? val : $(window)[ 'scrollLeft' ](),
						name == 'Top'  ? val : $(window)[ 'scrollTop'  ]()
					) :
					this[ 'scroll' + name ] = val;
			}) :
			
			// Return the scroll offset
			this[0] == window || this[0] == document ?
				self[ (name == 'Left' ? 'pageXOffset' : 'pageYOffset') ] ||
					$.boxModel && document.documentElement[ 'scroll' + name ] ||
					document.body[ 'scroll' + name ] :
				this[0][ 'scroll' + name ];
	};
});

$.fn.extend({
	position: function() {
		var left = 0, top = 0, elem = this[0], offset, parentOffset, offsetParent, results;
		
		if (elem) {
			// Get *real* offsetParent
			offsetParent = this.offsetParent();
			
			// Get correct offsets
			offset       = this.offset();
			parentOffset = offsetParent.offset();
			
			// Subtract element margins
			offset.top  -= num(elem, 'marginTop');
			offset.left -= num(elem, 'marginLeft');
			
			// Add offsetParent borders
			parentOffset.top  += num(offsetParent, 'borderTopWidth');
			parentOffset.left += num(offsetParent, 'borderLeftWidth');
			
			// Subtract the two offsets
			results = {
				top:  offset.top  - parentOffset.top,
				left: offset.left - parentOffset.left
			};
		}
		
		return results;
	},
	
	offsetParent: function() {
		var offsetParent = this[0].offsetParent;
		while ( offsetParent && (!/^body|html$/i.test(offsetParent.tagName) && $.css(offsetParent, 'position') == 'static') )
			offsetParent = offsetParent.offsetParent;
		return $(offsetParent);
	}
});

function num(el, prop) {
	return parseInt($.css(el.jquery?el[0]:el,prop))||0;
};

})(jQuery);

/* jquery.mousewheel.js */
(function(c){var a=["DOMMouseScroll","mousewheel"];c.event.special.mousewheel={setup:function(){if(this.addEventListener){for(var d=a.length;d;){this.addEventListener(a[--d],b,false)}}else{this.onmousewheel=b}},teardown:function(){if(this.removeEventListener){for(var d=a.length;d;){this.removeEventListener(a[--d],b,false)}}else{this.onmousewheel=null}}};c.fn.extend({mousewheel:function(d){return d?this.bind("mousewheel",d):this.trigger("mousewheel")},unmousewheel:function(d){return this.unbind("mousewheel",d)}});function b(f){var d=[].slice.call(arguments,1),g=0,e=true;f=c.event.fix(f||window.event);f.type="mousewheel";if(f.wheelDelta){g=f.wheelDelta/120}if(f.detail){g=-f.detail/3}d.unshift(f,g);return c.event.handle.apply(this,d)}})(jQuery);


/* JavaScript file */

$(function(){
        /* for main */
	var str = new String(window.location);
	if(str.indexOf("map")+1)
		return true;
	
	place = $('div.places div.place');
	$(place).hide(1);
	placeDraw(place);		
        /* end for main */
	$.ajaxSetup({cache: false});	
	$('ul.places_menu li a.sort').click(function(){
		var ref = $(this).next('span.ref').html();
		$.ajax({
			type: 'GET',
   			timeout: 2000,
	 		url: window.location+"?type=ajax&category="+ref,
	  		error: function() {
				return true;
			},
    			success: function(xml) {
				var objListHTML = new String("");
				$(xml).find('object').each(function() {
					var objName=$(this).attr('name');
					var objHREF=$(this).attr('href');
					var picture=$(this).find('picture').attr('src');
					var undertitle=$(this).find('undertitle').text();
					var brief=$(this).find('brief').text();
					var leftblock=$(this).find('leftblock').text();
					var rightblock=$(this).find('rightblock').text();
					var address=$(this).find('address').text();
					
					objListHTML+="<div class='place' style='display:none'><div class='item'><div class='pic'><a href='"+objHREF+"'><img width='218' height='127' src='"+picture+"' alt='"+objName+"'></a></div>";
					
					objListHTML+="<p>"+undertitle+"</p>";
					objListHTML+="<h1><a href='"+objHREF+"'>"+objName+"</a></h1>";
					objListHTML+='<p class="inf">'+brief+'</p>';
					if(leftblock || rightblock)
					{
						objListHTML+='<div class="area"><span>'+leftblock+'</span>';
						objListHTML+='<div>'+rightblock+'</div></div>';
					}
					objListHTML+='<div class="adress">'+address+'</div>';
					objListHTML+='</div></div>';
				});
				
				var places = $('div.places');
				//$(place).hide(1);
				var h = $(places).height();
				var w = $(places).width();
				$(places).css({height: h+"px", width: w+"px"});
				$(".places").html(objListHTML);
				
				place = $('div.places div.place');
				placeDraw(place);		
				
				$('ul.places_menu li:has("a.sort")').each(function(){
					var img=$(this).find('img');
					var src=img.attr('src');
					var curref=$(this).find('a').next('span.ref').html();
					if(curref == ref){
						$(this).addClass('active');
						$(this).find('img').attr('src',src.replace(new RegExp("_notactive",'g'),"_active"));
						document.title=img.attr("alt")+" - МонАрх";
					}else{
						$(this).removeClass('active');
						$(this).find('img').attr('src',src.replace(new RegExp("_active",'g'),"_notactive"));		
					}
				});
				
			}
		});
	//	placeSort(href);
		//document.title = pages[href]["title"];
//		$('.infob').innerHTML = pages[href]["footer"];
		//$('.infob').html(pages[href]["footer"]);
		return false;
	});
});

function placeSort (elem) {
	var places = $('div.places');
	var h = $(places).height();
	var w = $(places).width();
	$('div.place',places).hide(1);
	$(places).css({height: h+"px", width: w+"px"});

	
	if(elem == 'all') {
		place = $('div.place',places);
	} else {
		place = $('div.'+elem).parent();			
	}	
	
	placeDraw(place, elem);			

	$('ul.places_menu li:has("a.sort")').each(function(){
		if($(this).find('a').attr('ref') == elem){
			$(this).addClass('active');
			var img = $(this).find('a').attr('ref');			
			$(this).find('img').attr({src: '/img/places_'+img+'_btn_active.gif'});					
		}else{
			$(this).removeClass('active');
			var img = $(this).find('a').attr('ref');			
			$(this).find('img').attr({src: '/img/places_'+img+'_btn.gif'});
		}
	});
}

function placeDraw (place, type) {
	place.each(function (i) {
		var pl = $(this);
		$(pl).show(800, function() {
			if (i == 0) {
				var pp = $(this).parent();
				$(pp).css({height: "auto"});
			}
		});
		var complex_id = $(this).find('h1 a').attr('class');		
		if((typeof type != 'undefined') && (type != 'all')){			
			pl.find('a').attr('href', '/index/'+type+'/'+complex_id);
		}else if(type == 'all') {
			pl.find('a').attr('href', '/index/'+complex_id);
		}
/*		
		if((typeof type != 'undefined') && (type != 'all')){
			var str = pl.find('.pic a').attr('href');

			var getParams = {};
			(function(obj, str) {
				for (var ar = str.split("&"), i=ar.length, pair; i--;) {
				pair = ar[i].split("=");
				obj[ pair[0] ] = pair[1];
			}
			})(getParams, window.location.search.substr(1));
			alert(getParams.complex_id);
			
		}
*/
	});
	
/*
	place.each(function (i) {
		var pl = $(this);
		$(pl).css({height:"1px",overflow:"hidden",width:"1px",position:"relative"});
		$(pl).show(1, function() {
			var pos = $(this).position();
			var r = Math.round(Math.random()*10) - Math.round(Math.random()*10);
			var t = Math.random()*10;
			$(this).css({height:"auto",width:"auto",position:"absolute", left:(r*2000)+"px", top: (r*1000)+"px"});
			$(this).animate({opacity:1,left:pos.left+"px", top:pos.top+"px"}, t*120,function(){
				$(this).css({overflow:"visible",position:"static"});
			        if (i == 0) {
			        	var pp = $(this).parent();
			       		$(pp).css({height: "auto"});
			        }
			});
		});
	});

*/
}


/* waymap */
function initialize(l, a, z) {
	if (GBrowserIsCompatible()) {
		var map = new GMap2(document.getElementById("map_canvas"));
		var latlng = new GLatLng(l,a);
		var point = new GMarker(latlng);
		map.setCenter(latlng,z);
		map.addOverlay(point);
		map.addControl(new GSmallMapControl());
		map.addControl(new GMapTypeControl());
	}
}			
$(document).ready(function(){
	$('a.waymap_lnk').click(function(){
		//$('.object .passage').append('<div class="waymap"><img class="pngfix" src="/img/waymap_bg.png" width="376" height="377"><a class="waymap_close"><img class="pngfix" src="/img/waymap_close.png" width="40" height="40"/></a><div><iframe width="342" height="342" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" src="http://maps.google.ru/maps?f=q&amp;source=s_q&amp;hl=ru&amp;geocode=&amp;q='+waymap+'&amp;output=embed"></iframe></div></div>');
		$('.object .passage').append('<div class="waymap"><img class="pngfix" src="/img/waymap_bg.png" width="376" height="377"><a class="waymap_close"><img class="pngfix" src="/img/waymap_close.png" width="40" height="40"/></a><div class="gmap_cont"><div id="map_canvas"></div> </div></div>');
		var gdata = $('#gmap').val().split(",");
		var p1 = gdata[0];
		var p2 = gdata[1];
		var z0 = 15; // parseInt(gdata[2],10);
		initialize(p1,p2,z0);
		$(document).ready(function(){		
			$('a.waymap_close').click(function(){
				$('.object .passage .waymap').remove();	
			});	
		});
	});
});

/* on Moscow Map */
$(document).ready(function(){
	$('.objects_onmap .object .onmapstar').hover( function () {
			$(this).parent().addClass('object_act');
			$(this).hide();
	},function() {});
	$('.objects_onmap .object .info_full' ).mouseleave(function () {
		$(this).parent().removeClass('object_act');		
		$(this).parent().find('.onmapstar').show();
	});
});

/* object block menu */
$(document).ready(function(){
    $('.object_path li:has("ul")').hover(
        function() {
			$(this).addClass('active');
            $(this).find('ul').show();
        },
        function() {
			$(this).removeClass('active');		
            $(this).find('ul').hide();
        }
    );
});
/* pasaha  */

$(document).ready(function(){

	formsInit($('form.form'));
	setScrollGalF();

});
function setScrollGalF(){
	var twd = 0;
	var gal3 = $("#sc-gal3")
	
	if(!gal3.length) return;
	
	$("#sc-gal2 li").each(function(){
		twd += $(this).width()+13;
	})
	var tw = $("#sc-gal3").width()

	if(tw >= twd) {
	$("#sc-gal2.scroll-pane").removeClass('scroll-pane')
	return;
	};
	$("#sc-gal3").width(twd)
	$("#sc-gal2").jScrollHorizontalPane({scrollbarHeight:18, scrollbarMargin:0,showArrows :false,dragMinWidth:98,dragMaxWidth :98});



};

/**
 * Настойка форм
 */
function formsInit($o,dopFunc,ignorCheckFunc){
	
	var f = $o ? $o :$('form');

	if(!f.length )return;
	
	f.find('input:not(.submit),textarea,select').bind('focus',function(){
		$(this).addClass('focus')
	}).bind('blur',function(){
		$(this).removeClass('focus')
	})
	f.find('.failed:first input').trigger('focus');

//	var $defs = f.find('.f_labeled');
//	var $defsEls = $('input:last,textarea',$defs);
//	var $defsLabl = $('label',$defs);

//	$defsEls.blur()
//	$defsEls.bind('focus',focusFunc).bind('blur',blurFunc)
//	.each(initFunc)
//	$defsLabl.bind('click',function(){
//		$(this).next().children().children().focus()
//	})

	f.bind('submit', function(e){

		if(ignorCheckFunc && typeof dopFunc == 'function'){
			if(ignorCheckFunc(this)) e.preventDefault();
		}else if(this.unlock){
			return;
		}
		
		var ths = this;

		// Валидация перед отправкой
		
		var obj = $(this).find('input,textarea');
		var rq,sO;
		
		var req = obj.filter('.req');
	
		for(ii= 0; ii< obj.length;ii++){
			sO = obj.eq(ii);
			rq = sO.hasClass('req') ? !sO[0].value.length : false;
			if(checkErrors(sO[0],e,rq )) return false;
			
			//log(ii,obj.lenght,ii == obj.lenght-1 , !f[0].error , dopFunc , typeof dopFunc == 'function')
		
			if(ii == obj.length-1 && !this.error && dopFunc && typeof dopFunc == 'function'){
			//	log(dopFunc,f)
				dopFunc(this)
				return false;
			}
		
		}
		/*
		req.each(function(){
			checkErrors(this,e,!this.value.length,req )
		})

		if(!f[0].error){

			obj.not(req).each(function(){
				checkErrors(this,e,true,obj.not(req))
			})
		}
*/
	//	return false;
	});

	function checkErrors(o,e,dop){
			if(dop || checkDef(o)){

				initError(o,e)
				return true;
			}else{

				clearError(o)
				return false;
			}
	}


	function checkDef(o){

		var reMail = /^[0-9A-Za-z_\-\.]+@(?:[0-9A-Za-z\-]+\.)+[A-Za-z]{2,6}$/;
		var rePhone = /^[0-9]{3}[\- ]?[0-9]{2}[\- ]?[0-9]{2}$/;
		var rePhone2 = /\d{3}/;
		var rePhoneSing = /^((\+\d{1,3}(-| )?\(?\d\)?(-| )?\d{1,5})|(\(?\d{2,6}\)?))(-| )?(\d{3,4})(-| )?(\d{4})(( x| ext)\d{1,5}){0,1}$/;
		var rePhoneSing = /^(1\s*[-\/\.]?)?(\((\d{3})\)|(\d{3}))\s*[-\/\.]?\s*(\d{3})\s*[-\/\.]?\s*(\d{4})\s*(([xX]|[eE][xX][tT])\.?\s*(\d+))*$/;

		if((/m+a+i+l/).test(o.id) && ( o.value.length && !reMail.test(o.value)))
		{
			return true;
		}
		else if( o.id =='phone2' && ( o.value.length && !rePhone2.test(o.value) ))
		{
			return true;
		}
		else if( (/f+_+p+h+o+n+e/).test(o.id) && ( o.value.length && !rePhoneSing.test(o.value) ))
		{
			return true;
		}
		else if( o.id =='phone' && ( o.value.length &&  !rePhone.test(o.value)) || (document.getElementById('phone2') && document.getElementById('phone2').value.length && !o.value.length ))
		{
			
			return true;
		}else return false;
	//	return ((/m+a+i+l/).test(o.id) && !reMail.test(o.value)) ||
//		( o.id =='phone2' && ( o.value.length && !rePhone2.test(o.value) || (document.getElementById('phone').value.length && o.value.length ) )) ||
//		( o.id =='phone' && ( o.value.length &&  !rePhone.test(o.value)))		
 	}

	function initFunc(){
		if(this.value){$(this).parent().parent().prev().hide()}
	}
	function blurFunc(){
		if(!this.value){$(this).parent().parent().prev().show()}
	}
	function focusFunc(){
		$(this).parent().parent().prev().hide()		
	}

	function initError(o,e){
		$(o).trigger('focus').parents('.s-line,.line').addClass('failed')//.attr('title',$(o).parent().parent().prev().text());
		$(o).parents('form')[0].error = true;
		e.preventDefault();
	}
	function clearError(o){
		$(o).parents('.s-line,.line').removeClass('failed')//.removeAttr('title')
		$(o).parents('form')[0].error = false;
	}
}

