Array.prototype.in_array = function(p_val) {
	for(var i = 0, l = this.length; i < l; i++)	{
		if(this[i] == p_val) {
			return true;
		}
	}
	return false;
}

$(function(){
	var edit_news_links = $('.news-super-menu-open');
	var edit_news_menus = $('.news-super-menu'),
		timeoutVar;
	if( edit_news_links && edit_news_links.length > 0 ){
		edit_news_links.each(function(){
			$(this).click(function(){
				clearTimeout(timeoutVar);
				var menu = $(this).parents().filter('.super-news-point').find('.news-super-menu');
				edit_news_menus.not(menu).hide();
				menu.toggle();
				menu.mouseenter(function(){
					clearTimeout(timeoutVar);
				}).mouseleave(function(){
					timeoutVar = setTimeout(function(){
						menu.hide();
					},3000);
				});
				timeoutVar = setTimeout(function(){
					menu.hide();
				},3000);
			});
		});
	}
	

	var sectionTitle = $("#section_title");
	var sectionTitleValue = sectionTitle.text();
	if( sectionTitleValue.length == 0 ){
		var local = new Date(),
			hours = local.getHours(),
			timeOfDay;
		if (hours < 12) {
			timeOfDay = "доброе утро";
		} else if (hours < 17) {
			timeOfDay = "добрый день";
		} else if (hours <= 23) {
			timeOfDay = "добрый вечер";
		}
		sectionTitle.text(timeOfDay);	
	}
	
	var _search_input = $('#search_input');
	if( _search_input.length ) _search_input.defval('Поиск...');
	
});

var controlEvent = {
	button:{'ctrl':false,'alt':false,'shift':false,'enter':false},
	functions:{},
	call:function(event){
		if(!event) var event = window.event;
		var keycode = event.keyCode ? event.keyCode : event.which ? event.which : null;
		if(event.type=='keydown') controlEvent.keyDown(event,keycode);
		if(event.type=='keyup') controlEvent.keyUp(event,keycode);
	},
	init_functions:function(array){
		for (var key in array){
			var func = array[key];
			if( typeof func == 'function' ) func();
		}
	},
	ctrlenter:[],
	shiftenter:[],
	keyDown:function(event,keycode){
		if( keycode == 17 ) controlEvent.button.ctrl = true;
		if( keycode == 18 ) controlEvent.button.alt = true;
		if( keycode == 16 ) controlEvent.button.shift = true;
		if( keycode == 13 ) controlEvent.button.enter = true;
		if( controlEvent.button.ctrl && controlEvent.button.enter ) 
			controlEvent.init_functions(controlEvent.ctrlenter);
		if( controlEvent.button.shift && controlEvent.button.enter ) 
			controlEvent.init_functions(controlEvent.shiftenter);
	},
	keyUp:function(event,keycode){
		if( keycode == 17 ) controlEvent.button.ctrl = false;
		if( keycode == 18 ) controlEvent.button.alt = false;
		if( keycode == 16 ) controlEvent.button.shift = false;
		if( keycode == 13 ) controlEvent.button.enter = false;
	},
	bind:function(array,callback){
		var string = array.join('').toLowerCase();
		if( string=='ctrlenter' || string=='enterctrl' ) controlEvent.ctrlenter.push(callback);
		if( string=='shiftenter' || string=='entershift' ) controlEvent.shiftenter.push(callback);
		return controlEvent;
	}
}

if( document.addEventListener ){
	document.addEventListener('keydown', controlEvent.call,false);
	document.addEventListener('keyup', controlEvent.call,false);
}else if( document.attachEvent ){
	document.attachEvent('onkeydown', controlEvent.call);
	document.attachEvent('onkeyup', controlEvent.call);
}

(function () {
	var $html = $('html'),
		fontFaceClass;

	$html.addClass('js');

	// Allow custom styles for users with narrower screens.
	if (screen.availWidth < 1110) {
		$html.addClass('narrow');
	}

	// If Firefox 3.5+, hide content till load (or 3 seconds) to prevent FOUT
	if (document.documentElement.style.MozTransform === '') { // gecko 1.9.1 inference
		fontFaceClass = 'hide-custom-font-face';
		$html.addClass(fontFaceClass);
		setTimeout(function () {
			$html.removeClass(fontFaceClass);
		}, 500);
	}
}( ));

// IZHCITY written functions that have global reach go here
Date.prototype.lastSunday = function () {
	var dateOnSundayWithTime = new Date(this.getTime() - (this.getDay() * 24 * 60 * 60 * 1000 ));
	return new Date(dateOnSundayWithTime.getFullYear(), dateOnSundayWithTime.getMonth(), dateOnSundayWithTime.getDate() );
};

Date.prototype.dateOnlyString = function () {
	return (this.getMonth() + 1 ) + "/" + this.getDate() + "/" + this.getFullYear();
};


var analytics = {

    uid : function(){
        var uid = this.getCookie();
        if( uid == null || uid == '' )
        {
            uid = this.setCookie();
        }

        return uid;
    },
    buildNewUID : function(){
        return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
            var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
            return v.toString(16);
        });
    },
	getCookie : function(){
        return IZHCITY.readCookie( 'random_uid' );
    },
    setCookie : function(){
		// var uid = this.buildNewUID();
		//IZHCITY.writeCookie( 'random_uid', uid, 900 );
		return uid;
    }

};

function resetText (id,text) {
	if ($(id).val() === '') {
		$(id).val(text);
	}
}

function clearForm (id, value) {
	if ($(id).val() === value) {
		$(id).val('');
	}
}

//////////////////////////
// Create the IZHCITY namespace
//////////////////////////

var IZHCITY = {
	link_window:function(link,width,height){
		var _title = link.title || '',
			width = width || 400,
			height = height || 200;
		var _window = window.open(
			link.href,
			_title,
			'width='+width+','+
			'height='+height+','+
			'resizable=yes,'+
			'scrollbars=yes,'+
			'toolbar=no,'+
			'status=yes'
		)
		_window.focus();
		return false;
	},
	subscribe_action:false,
	subscribe:function( form, complete, error ){
		
		if( IZHCITY.subscribe_action ) return false;
		IZHCITY.subscribe_action = true;
		
		var $form = $(form);
		
		$form.fadeTo(200, 0.6);
		
		var _data_string = $form.serialize();
		var complete = ( typeof complete == 'function' )? complete : function(){};
		var error = ( typeof error == 'function' )? error : function(){};
		$.post('/json/mail/subscribe/',_data_string,function(data){
			if( data.systemContent == false ){
				error( data.error );
			}else{
				complete( data.message );
			}
			$form.fadeTo(100, 1);
			IZHCITY.subscribe_action = false;
		},'json');
		
		return false;
	},
	removeComment:function(id,link){
		$block = $(link).parents().filter('.comment-point-advance');
		$.post('/json/comments/remove/',{id:id},function(data){
			if( data.systemContent == false ){
				alert(data.error);
			}else{
				$block.remove();
			}
		},'json');
	},
	alert:function(text,options){
		var _options = {
			width	: 300,
			height	: 'auto',
			title	: false,
			top		: 150
		},
		alert_block,
		title_block,
		close_button,
		content_block,
		scrollPosition = 0,
		overlay_block;
		
		var options = options || _options;
		
		if( options ) $.extend( _options, options );
		
		if ( document.documentElement && document.documentElement.scrollTop )
			// IE6 +4.01 and user has scrolled
			scrollPosition = document.documentElement.scrollTop;
		else if ( document.body && document.body.scrollTop )
			// IE5 or DTD 3.2
			scrollPosition = document.body.scrollTop;
		else if ( document.scrollTop )
			scrollPosition = document.scrollTop;
		
		if( $.browser.msie && $.browser.version < 7 ) var _position = 'absolute';
		else var _position = 'fixed';
		
		overlay_block = $('<div class="izhcity_alert_block_overlay"></div>').css({
			position : _position,
			width : '100%',
			height : '100%',
			top : 0,
			left : 0,
			zIndex : 99991,
			background : '#000000',
			opacity : 0.4
		}).appendTo('body');
		
		alert_block = $('<div class="izhcity_alert_block"></div>').css({
			position : 'absolute',
			width : options.width,
			top : scrollPosition + options.top,
			left : '50%',
			zIndex : 99999,
			marginLeft : (-( Math.round( options.width / 2 ) ))
		}).appendTo('body');
		
		function closeWindow(){
			alert_block.remove();
			overlay_block.remove();
		}
		
		overlay_block.click(closeWindow);
		
		title_block = $('<div class="izhcity_alert_block_title"></div>').appendTo(alert_block);
		
		title_block.html( 
			close_button = $('<a class="izhcity_alert_block_close"><span></span></a>').click(closeWindow)
		);
			
		content_block = $('<div class="izhcity_alert_block_content"></div>').appendTo(alert_block);
		
		content_block.html(text);
	},
    cache_buster: 0,

	// A flag for testing DOM-readiness
	domReady: (function () {$(function () {IZHCITY.domReady = true;});return false;})( ),

	// Returns a new copy of an object (not a reference)
	beget: function (o) {
		var F = function () {};
		F.prototype = o;
		return new F();
	},

	reloadAllAdsOnPage: function () {
		var self = this;
		$('iframe.vendor_ad').each(function () {
			var original_source = $(this).attr("src");
			original_source = original_source.replace( /&cache_buster=[0-9]*/i, '' ) + "&cache_buster=" + self.cache_buster;
			self.cache_buster += 1;
			$(this).attr({
				src: original_source
			});
		});
		return false;
	},

  isValidEmail : function( email )
  {
    return email.match( /^[a-z0-9!#$%&\'*+\/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&\'*+\/=?^_`{|}~-]+)*@(?:[a-z0-9][-a-z0-9]*\.)*(?:[a-z0-9][-a-z0-9]{0,62})\.(?:(?:[a-z]{2}\.)?[a-z]{2,4}|museum|travel)$/i );
    return false;
  },

	writeCookie: function (name, value, days, path) {
		var date = new Date(), expiry;

		if( days ){
			date.setTime(date.getTime() + days * 8.64e7);
			expiry = date.toUTCString();
		}else{
		  expiry = '';
		}

		path = path || '/';
		document.cookie = [name + '=' + value, 'expires=' + expiry, 'path=' + path].join('; ');
		return this.readCookie(name);
	},

	readCookie: function (name) {
		var nameEQ = name + "=",
			ca = document.cookie.split(';'),
			c;

		for (var i=0; i<ca.length; i++) {
			c = ca[i];

			if (c.charAt(0) === ' ') {
				c = c.substring(1,c.length);
			}

			if (c.indexOf(nameEQ) === 0) {
				return unescape(c.substring(nameEQ.length,c.length));
			}
		}

		return null;
	},

	deleteCookie: function(name){
		return this.writeCookie(name, '', -1);
	},

	user: function() {

		var cookie = this.readCookie('izhcity_cookies'),
			user;

		if (cookie) {
			cookie = cookie.split('|');
			user = {
				link: '/community/view/login/' + cookie[0],
				name: cookie[1] && cookie[1].replace('+',' '),
				image: ( cookie[2] && cookie[2].length>3 )? '/uploads/images/avatar/30/' + cookie[2] : '/templates/main/images/defaults/avatar30.jpg',
				fb: cookie[3] > 0,
				access: cookie[4] && cookie[4] === '1'
			};
		} else {
			user = false;
		}

		return user;
	},

	// Helper method for calling ui.dialog and referencing already-open dialogs
	// The options parameter can be used to override default UI dialog options.
	// Additionally, options can accept the following non-UI properties:
	//	url: Sets the url for the $.load request (default: event's target.href)
	//	html: The selector that queries or creates the $dialog jQuery object (default: '<div/>')
	dialog: function (selector, options) {
		var $dialog = $(options && options.html || '<div/>');

		function open(url, config){
			if (url) {
				$.ajax({
					url: url,
					success: function (html) {
						var $html = $(html);
						$(function () {
							IZHCITY.form.animateAndReplace($dialog.children(), $html, {
								hide: ($.support.opacity) ? ['puff', {percent:100}, 200] : ['slide', {}, 0] ,
								show: ['slide', {direction:'up'}, 200],
								after: function ($old, $new) {
									var $dialogContainer = IZHCITY.form.getAncestor($new, '.ui-dialog');
									$dialogContainer.animate(
										{top:($(document).scrollTop() + ($(window).height() - $dialogContainer.outerHeight()) / 2)},
										{
											duration: 100,
											complete: function () {
												$dialog.dialog('option', 'position', 'center');
											}
										}
									);
								}
							});
						});
					}
				});
				$dialog.html('<div class="loading"/>');
			}

			$dialog.bind('dialogclose', function(){
					$(this).dialog('destroy').remove();
				}).dialog(config)
				// Add a title attribute to the close button for added accessibilty
				.parent()
					.find('.ui-dialog-titlebar-close')
						.attr('title', 'Нажмите здесь, чтобы закрыть эту панель.')
						.end()
					.end()
				.dialog('open');
		}

		// Extend dialog defaults with any specified options
		options = $.extend({
			autoOpen: false,
			bgiframe: true,
			iframe: false,
			modal: true,
			resizable: false,
			closeText: '',
			closeOnEscape: true,
			width: 600
		}, options);

		if (selector) {
			$(selector).each(function (i) {
				options.title = options.title || this.title;
				$(this).unbind().click(function (e) {
					e.preventDefault();
					open(options.url || this.href, options);
				});
			});
		} else {
			open(options.url, options);
		}

		return $dialog;
	},

	// Helper funciton for calling a login dialog and handling any interrupted actions
	login: function (postId) {
		IZHCITY.dialog(null, {
			url:'/users/login' + ('/' + postId || ''),
			title:'Войти в IZHCITY'
		});
	},

	// Checks for an existing association b/w Facebook and IZHCITY user account
	facebookLogin: function(){
		FB.login(function(response) 
		{
			if (response.session) 
			{
				var fbuid = response.session.uid;
				FB.api('/me', function(response){
					var first_name = response.first_name;
					var last_name = response.last_name;
					var picture = "http://graph.facebook.com/" + fbuid + "/picture";
					$.ajax({
						type: "GET",
						url: "/users/facebook_login",
						data: "last_name=" + last_name + "&first_name=" + first_name + "&fbuid=" + fbuid + "&picture=" + picture,
						success: function(msg)
						{
							window.location.reload();
						}
					});
				});
			} else {
				window.location.reload();
			}
		});    
	},

	// Populate profileArea	(called within page)
	populateProfile: function ($profile) {
		var user = this.user(),
			$loggedInBox = $('\
				<div class="you">\
					<a class="profile-link polaroid"><span class="profile-image"></span></a>\
					<ul>\
						<li><a class="profile-link">Профиль</a></li>\
						<li><a href="/admin/posts/add">Создать публикацию</a></li>\
						<li><a href="/admin/gallery/add">Добавить фото</a></li>\
						<li><a href="/users/edit">Настройки</a></li>\
						<li class="signout"><a href="/logout">Выйти</a></li>\
					</ul>\
				</div>');
		
		if (user && user.access){
			$loggedInBox
				.find('li')
				.eq(1)
				.after('\
					<li><a href="/admin/posts/add">Создать публикацию</a></li>\
					<li><a href="/admin/posts/new_job">Создать Вакансию</a></li>\
					<li><a href="/admin/posts/new_press">Новый пресс релиз</a></li>\
					<li><a href="/admin/posts">Управление</a></li>\
				');
		}

		if(user){
			$profile.empty();

			$loggedInBox
				.find('.profile-link')
					.attr('href', user.link)
					.end()
				.find('.profile-image')
					.css({
						display:'block',
						width:30,
						height:30,
						backgroundImage:'url('+user.image+')',
						backgroundPosition:'0 0',
						backgroundRepeat:'no-repeat'
					});

			if (user.fb){
				$loggedInBox.find('[href="/users/logout"]').click(function(e){
					e.preventDefault();
					FB.logout(function (){
						window.location='/users/logout';
					});
				});
			}


			$profile
				.append($loggedInBox)
				.removeClass('not-logged-in')
				.addClass('logged-in');

		}else{

//			IZHCITY.dialog($profile.find('a[href=/login], a[href=/users/signup]'));

		}

		$profile.show();
	},

	loadScript: function (src, callback) {
		var referenceElement, script;
		if (typeof callback === 'function') {
			$.getScript(src, callback);
		} else {
			referenceElement = document.getElementsByTagName('script')[0];
			script = document.createElement('script');
			script.type = 'text/javascript';
			script.async = true;
			script.src = src;
			referenceElement.parentNode.insertBefore(script, referenceElement);
		}
	},
	
	importantNews: function ( id, type ) {
		$.post('/json/posts/important/',{id:id, type:type},function( data ){
			if( data.systemContent == false ){
				IZHCITY.alert( data.error );
			}else{
				var _message = ( type == 'display' )? 
					'Новость успешно опубликована на главной' : 
					'Новость успешно убрана с главной';
				IZHCITY.alert( _message );
			}
		},'json');
	},
	
	removeNews:function ( id ) {
		if (confirm('Вы уверены, что хотите навсегда удалить новость?')) {
			$.post('/json/posts/destroy/',{id:id},function( data ){
				if( data.systemContent == false ){
					IZHCITY.alert( data.error );
				}else{
					IZHCITY.alert( 'Новость успешно удалена' );
				}
			},'json');
		}
	},
	
	loadStyle: function ( src, callback ){
		var _css_prepare = document.createElement('link');
		_css_prepare.setAttribute('rel', 'stylesheet');
		_css_prepare.setAttribute('type', 'text/css');
		_css_prepare.setAttribute('href', src);
		
		if( typeof _css_prepare != 'undefined' )
			document.getElementsByTagName('head')[0].appendChild( _css_prepare );
		if( typeof callback == 'function' )
			callback();
	}


};

