var main_host;
$(document).ready(function(){

	auto_what_init("#what");
	auto_where_init("#where");

	auto_where_map_init("#where_map");

	//Get IMG Links
	/*
		$(".screenshot").slimbox({}, null, function(el) {
			return (this == el) || ((this.rel.length > 8) && (this.rel == el.rel));
		});
		*/
		$('#search_button').mousedown(function(){$(this).addClass('clicked');}).mouseup(function(){$(this).removeClass('clicked');}).mouseout(function(){$(this).removeClass('clicked');});
		//$(document).bind('mouseup', function(){$(this).removeClass('clicked');});
//	parseTabs();
	if(main_host==undefined)
		var main_host = '';

	document_ready_flag = 1;
	
	$('#add_firm_button').mousedown(function(){ $(this).addClass('add_firm_button_clicked')}).
	mouseup(function(){$(this).removeClass('add_firm_button_clicked')}).
	mouseout(function(){$(this).removeClass('add_firm_button_clicked')}).focus(function(){$(this).blur()})
});

var Device = {};

Device.isiPhone = function() {
	return navigator.userAgent.indexOf('iPhone') != -1;
}
Device.isiPod = function() {
	return navigator.userAgent.indexOf('iPod') != -1;
}
Device.isiPad = function() {
	return navigator.userAgent.indexOf('iPad') != -1;
}
Device.isiOS = function() {
	return Device.isiPhone || Device.isiPod || Device.isiPad;
}


function detectIE6()
{
	var browser = navigator.appName;
	var b_version = navigator.appVersion;
	var version = parseFloat(b_version);
	if ((browser == "Microsoft Internet Explorer") && (version <= 6))
	return true;
	else
	return false;
}


var tabs = new Array()
function mouseDownSearchButton(obj){
	obj = $(obj);




}

function selectTopPanel(obj, id_show_block){
	obj = $(obj);
	if(obj.hasClass('act'))
		return false;

	var li = $('#main_panel .main_panel_select');
	li.find('*').removeClass('bg l_c_act r_c_act act l_c_act_notfirst')
	// делаем вкладку активной
	li = obj.parent()
	li.addClass('act');
	if(li.hasClass('first'))
		obj.prev().addClass('bg l_c_act')
	else
		obj.prev().addClass('bg l_c_act_notfirst')
	obj.next().addClass('bg r_c_act')
	obj.addClass('act');

	$('#search_blocks .select_block').hide();
	$('#'+id_show_block).show();
}

function selectMainBlock(obj, id_show_block){
	obj = $(obj);
	if(obj.hasClass('act'))
		return false;

	var li = obj.parent().parent();
	var ul = li.parent();
	ul.find('.act').removeClass('act')
	ul.find('.act_first').removeClass('act_first')

	obj.addClass('act')
	li.addClass('act')
	ul.find('.prev').removeClass('prev');
	if(li.hasClass('first'))
		li.find('div').addClass('act_first');
	else{
		li.prev().addClass('prev');
	}

	ul.parent().parent().next().find('.selected_blocks .selected_block').hide();
	//$('.selected_blocks .select_block').hide();
	$('#'+id_show_block).show();
	// Парсим url
	var anchor = obj.attr('href');


}

function submitFormSearch()
{
	if($('#what').hasClass('input_hind'))
		$('#what').attr('value','')

	if($('#where').hasClass('input_hind'))
		$('#where').attr('value','')
		
}

function selectSubMenuBlock(obj, id_show_block){
	obj = $(obj);
	if(obj.hasClass('act'))
		return false;

	var li = obj.parent().parent();
	var ul = li.parent();
	ul.find('.act').removeClass('act')
	ul.find('.act_first').removeClass('act_first')
	ul.find('.act_last').removeClass('act_last')

	obj.addClass('act')
	li.addClass('act')
	ul.find('.prev').removeClass('prev');
	if(li.hasClass('first'))
		li.addClass('act_first');
	else{
		li.prev().addClass('prev');
	}

	if(li.hasClass('last'))
		li.addClass('act_last');
	else{
	}


	ul.parent().next().find('.sub_selected_block').hide();
	//$('.selected_blocks .select_block').hide();
	$('#'+id_show_block).show();

//	return false;

}

function setMenu(module){
	//alert(module)
	var li = $('#'+module+'_mark');
	
	if(li.hasClass('first'))
	{
		li.addClass('first_act');
	}
	else
	{
		li.addClass('act');
		//li.prev().addClass('prev');
	}
}

function setInputHind(id){
	var obj = $('#'+id);
	obj.addClass('input_hind');
	obj.attr('value',obj.attr('title'));
}

function unsetInputHind(id){
	var obj = $('#'+id);
	obj.removeClass('input_hind');
	obj.attr('value','');
}

function enableInputHind(id){

	var obj = $('#'+id);

	if(obj.attr('value')=='')
			setInputHind(id);

	obj.blur(function(){
		if(obj.attr('value')=='')
			setInputHind(id);
	});

	obj.focus(function(){
		if(obj.hasClass('input_hind'))
			unsetInputHind(id);
	});

	//obj.removeClass('input_hind');
	//obj.attr('value','');
}
function clickSearchWhat(id){
	$('#'+id).focus();
}

function showCitiesSelect(){
	var  select = $('#cities_select');
	var click_document=false;
	var clickDocument = function(){
//		alert('aaa');
		if(!click_document){ click_document=true;return;}
		select.animate({opacity: "hide"},'fast');
		$(document).unbind('click',clickDocument);
		click_document = false;
		//$(document).unbind('click',clickDocument);
	}

	if(select.css('display')=='none'){
		//select.show();
		select.animate({opacity: "show"},'fast');

		$(document).bind('click',clickDocument);

	}else{
		//select.hide();
	}

}

function toggleMyLocationBlock()
{
	var  select = $('#my_location_block');
	var click_document = false;
	var clickDocument = function(){
		if(!click_document)
		{
			//click_document=true;
			return;
		}

		select.animate({opacity: "hide"},'fast');
		$(document).unbind('click',clickDocument);
		click_document = false;
	}

	if(select.css('display')=='none')
	{
		click_document = true;

		select.find('#edit_my_location').hide().prev().show();
		select.animate({opacity: "show"},'fast', function(){

			$(document).bind('click',clickDocument);

		});

	}
	else
	{

	}

	$(document).bind('unbind',clickDocument);
	select.find('.ajax_link').click(function(){
		//alert('link');
		click_document = false;
		$(document).bind('unbind',clickDocument);
		select.find('#edit_my_location').show().prev().hide();

	})

}
/*
function showAdressSelect(){
	var  select = $('#my_location_block');
	var click_document=false;
	var clickDocument = function(){
//		alert('aaa');
		if(!click_document){ click_document=true;return;}
		select.animate({opacity: "hide"},'fast');
		$(document).unbind('click',clickDocument);
		click_document = false;
		//$(document).unbind('click',clickDocument);
	}

	if(select.css('display')=='none'){
		//select.show();
		select.animate({opacity: "show"},'fast');

		$(document).bind('click',clickDocument);

	}else{
		//select.hide();
	}

}
*/
/**
  * устанавливает вкладку и показывает соответствующий главны блок
  * со связями parent child.
  *
  * @param id_block ид элемента в котором находятся табы и переключаемые блоки
  * @param num_mark номер вкладки по порядку начиная с 1
  * @return func Функция вызываемая при установки вкладки, например аякс загрузка
  */
function setMainBlock(id_block, num_mark, func){
	num_mark--;
	var main_block = $('#'+id_block);
	var selected_block = main_block.find('.selected_blocks > div:eq('+num_mark+')');

	var li = main_block.find('.menu ul > li:eq('+num_mark+')');
	if(func==undefined)
		selectMainBlock(li.find('a'), selected_block.attr('id'));
	else
		func(li.find('a'), selected_block.attr('id'))
}

/**
  * устанавливает вкладку и показывает соответствующий подблок
  * со связями parent child.
  *
  * @param id_block ид элемента в котором находятся табы и переключаемые блоки
  * @param num_mark номер вкладки по порядку начиная с 1
  * @return func Функция вызываемая при установки вкладки, например аякс загрузка
  */
function setSubBlock(id_block, num_mark, func){
	num_mark--;
	var sub_block = $('#'+id_block);
	var selected_sub_block = sub_block.find('.selected_blocks > div:eq('+num_mark+')');

	var li = sub_block.find('.sub_menu_block ul > li:eq('+num_mark+')');
	//alert(li.html());
	if(func==undefined)
		selectSubMenuBlock(li.find('a'), selected_sub_block.attr('id'));
	else{
		func(li.find('a'), selected_sub_block.attr('id'))
		selectSubMenuBlock(li.find('a'), selected_sub_block.attr('id'));
	}
}

function setNumTabs(num_menu, num_tab){
	tabs[(num_menu-1)*2]=num_tab;
	document.location.hash='url='+tabs.join('_');
}

function setNumSubTabs(num_menu, num_tab, num_sub_tab){
	tabs[(num_menu-1)*2]=num_tab;
	tabs[(num_menu-1)*2+1]=num_sub_tab;
	document.location.hash='url='+tabs.join('_');
}

function showMyLocation(obj){

	obj = $(obj)
	//var par = obj.parent();
	var rules = $('#my_location_block');
	var left = obj.position().left+obj.width()-260;
	var top = obj.position().top-50;
	//par.css('position','relative');
 	//alert(left);
	rules.css({'left':left,'top':top}).removeClass('hide');


	return false;
}

function hideMyLocation(){

	$('#my_location_block').addClass('hide');

	return false;

}


function showAddLocationForm(){
	var  select = $('#add_location_form');
	var click_document=false;
	var clickDocument = function(){
//		alert('aaa');
		if(!click_document){ click_document=true;return;}
		select.animate({opacity: "hide"},'fast');
		$(document).unbind('click',clickDocument);
		click_document = false;
		//$(document).unbind('click',clickDocument);
	}

	if(select.css('display')=='none'){
		//select.show();
		select.animate({opacity: "show"},'fast');

		$(document).bind('click',clickDocument);

	}else{
		//select.hide();
	}

}

function add_location_ajax()
{
	var adress_location = $('#adress_location');
	var name_location = $('#name_location');

	var location = adress_location.val();
	var name = name_location.val();

	$.ajax({
  		 type: "POST",
  		 data: "location="+location+"&name="+name,
   		 url: "/cabinet/add_location/",
   		 success: function(data)
		 {
   		 	if(data==''||data=='error')
   		 		return;

   		 	data = data.split('&&');

   		 	var html_edit = '';
   		 	var html_list = '';

			for(var i in data)
			{
				adress = data[i].split('||');

				html_edit+= '<li>'+adress[1]+':'+adress[2]+'<a onclick="return delete_location_ajax('+adress[0]+')" href="javascript:" class="ajax_link">удалить</a></li>';
				html_list+= '<li><span>'+adress[1]+'</span>'+'<a onclick="return changeLocation("'+adress[2]+'")" href="/search/?where='+adress[2]+'" class="ajax_link">'+adress[2]+'</a></li>';
			}

			$('#edit_my_location ul').html(html_edit);
			$('#adress_select ul').html(html_list);

			adress_location.val('');
			name_location.val('');

   		 	//$('#my_location_ul').html(data);
   		 	//selectSubMenuBlock(obj,id_block);
  		 }
 	});
}

function delete_location_ajax(id_location){

	if(!confirm('Уверены, что хотите удалить данный адрес?'))
		return false;
	$.ajax({
  		 type: "POST",
  		 data: "id_location="+id_location,
   		 url: "/cabinet/delete_location/",
   		 success: function(data)
		 {
			if(data=='error')
   		 		return;

   		 	var html_edit = '';
   		 	var html_list = '';

			if(data)
			{
				data = data.split('&&');
				for(var i in data)
				{
				   adress = data[i].split('||');

					html_edit+= '<li>'+adress[1]+':'+adress[2]+'<a onclick="return delete_location_ajax('+adress[0]+')" href="javascript:" class="ajax_link">удалить</a></li>';
					html_list+= '<li><span>'+adress[1]+'</span>'+'<a onclick="return changeLocation("'+adress[2]+'")" href="/search/?where='+adress[2]+'" class="ajax_link">'+adress[2]+'</a></li>';
				}
			}

			$('#edit_my_location ul').html(html_edit);
			$('#adress_select ul').html(html_list);
  		 }
 	});
}

function changeLocation(location){

	removeLableSearch($('where'));
	unsetInputHind("where");
	$("#where").attr('value',location);
	selectLocation();
	return false;
}

function followObject(id_follower, type, follow, obj){

	$.ajax({
  		 type: "POST",
  		 data: "id_follower="+id_follower+"&type="+type+"&follow="+follow,
   		 url: "/cabinet/follow_object/",
   		 success: function(data){
   		 	obj = $(obj).parent();

   		 	if(follow){
   		 		obj.find('.spy_object').hide();
   		 		obj.find('.no_spy_object').show();
   		 	}
   		 	else{
   		 		obj.find('.spy_object').show();
   		 		obj.find('.no_spy_object').hide();

   		 	}


  		 }

 	});

}

function followResponse(id_follower){
	if(follower_response_hide)
		follower_response_hide = 0;
	else
		follower_response_hide = 1;

	$.ajax({
  		 type: "POST",
  		 data: "id_follower="+id_follower+"&type=response"+"&follow="+follower_response_hide,
   		 url: "/ajax/follow_object/",
   		 success: function(data){


   		 		//$(obj).click(function(){followObject(id_follower, 'response', follow, obj)});
   		 		//$('#follower_response').attr('onclick',"followObject(id_follower, 'response', follow, obj)");


  		 }

 	});

}

function unFollowDiscuss(id_follower, type, obj){

	$.ajax({
  		 type: "POST",
  		 data: "id_follower="+id_follower+"&type="+type+"&follow=0",
   		 url: "/ajax/follow_object/",
   		 success: function(data){
			$(obj).after('<span class="grey_text">принято</span>');
   		 	$(obj).remove();
  		 }

 	});
}


function showFullResponse(obj){

	//$('#min'+id_response).css('display','none');
	obj = $(obj);
	var comment =  $(obj).parent().parent();
	var min = comment.find('.min');
	var full = comment.find('.full')
	if(min.css('display')=='none'){
		min.show();
		full.hide();
	}else{
		min.hide();
		full.show();

	}
	obj.hide();
//	$('#full' + id_response).show();
//	$('#min'+id_response).hide();

	return false;

}

/*
function delete_cookie( cookie_name )
{
  var cookie_date = new Date ( );  // Текущая дата и время
  cookie_date.setTime ( cookie_date.getTime() - 1 );
  document.cookie = cookie_name += "=; expires=" + cookie_date.toGMTString();
}

function get_cookie( cookie_name )
{
  var results = document.cookie.match ( '(^|;) ?' + cookie_name + '=([^;]*)(;|$)' );

  if ( results )
	return ( unescape ( results[2] ) );
  else
	return null;
}
*/

function fixPNG(element,method,noIE)
{

  var methd;
  if (!method) methd='scale'
  else methd=method;
  if (/MSIE (5\.5|6).+Win/.test(navigator.userAgent))
  {
	var src;
	if (element.tagName=='IMG')
	{
	  if (/\.png$/.test(element.src))
	  {
		src = element.src;
		element.src = "i/x.gif";
	  }
	}
	else
	{
	  src = element.currentStyle.backgroundImage.match(/url\("(.+\.png)"\)/i);
	  if (src)
	  {
		src = src[1];
		element.runtimeStyle.backgroundImage="none";
		if (noIE) return;

	  }
	}
	if (src)
	{
	   element.runtimeStyle.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + src + "',sizingMethod='"+methd+"')";

	}
  }
}


/**
 * Голосование за спец. предложение
 * @param id_special
 * @param vote
 * @param obj
 * @return
 */
function voteSpecial(id_special,vote,obj)
{
	$.ajax({
  		 type: "POST",
   		 url: "/special/vote_special/",
   		 data: "id_special="+id_special+"&vote="+vote,
   		 success: function(data){
   		 	//$(obj).parent().html('<div style="margin-left:5px;">Спасибо</div> <div style="margin-left:5px;">за голос</div>');
			$(obj).parent().html(data);

  		 }
 	});
 	return false;
}


// Обратная php функции htmlspecialchars()
function htmlToChars(str)
{
	re = /&amp;/g;
	str=str.replace(re,'&');

	re = /&lt;/g;
	str=str.replace(re,'<');

	re = /&gt;/g;
	str=str.replace(re,'>');

	re = /&quot;/g;
	str=str.replace(re,'"');

	return str;
}


function insertVKButton(obj, url, title, description)
{
 	obj.html(VK.Share.button({url: url, type: "round", text: "Сохранить", title: title, description: description, noparse:true}));
}

function insertFBButton(obj, href)
{
	var iframe_html ='<iframe src="http://www.facebook.com/plugins/like.php?href='+href+'&amp;layout=button_count&amp;show_faces=false&amp;width=100&amp;action=like&amp;font&amp;colorscheme=light&amp;height=21" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:124px; height:21px;" allowTransparency="true"></iframe>';		
	obj.html(iframe_html);  	
}

function insertTVButton(obj, url, text)
{
	//var a_html = '<a href="http://twitter.com/share?url='+url+'&amp;text='+text+'" class="twitter-share-button">Tweet</a>';
	var a_html = '<iframe allowtransparency="true" frameborder="0" scrolling="no" src="http://platform.twitter.com/widgets/tweet_button.html?url='+url+'&text='+text+'" style="width:102px; height:20px;"></iframe>';

	obj.html(a_html);
}

function insertLJButton(obj, subject, a_href, a_text, text)
{
	var link = '<a href="'+a_href+'">'+a_text+'</a>';
	var a_html = '<form target="_blank" method="post" action=http://www.livejournal.com/update.bml name="updateForm"><div style="display:none;visible:false"><input type="text" maxlength="100" name="subject" id="subject" class="text" size="43" value="'+subject+'"/><textarea rows="1" cols="1" name="event">'+text+'<br/><br/>'+link+'</textarea></div><input class="jj_submit" type="submit" value=""></form>';
	obj.html(a_html);  	
}

function insertGPButton(obj, href)
{
	obj.html('<g:plusone size="small" href="'+href+'"></g:plusone>');  	
	gapi.plusone.go();
}


function makeLikesforBranch(obj,host,id_branch,name)
{
	if(!document_ready_flag)
	{
		$(document).ready(function()
		{
			$(obj).parent().prepend('<div id="vk_but'+id_branch+'" class="vk_but"/><div id="fb_but'+id_branch+'" class="fb_but"/><div id="tw_but'+id_branch+'" class="tw_but"/><div id="gp_but'+id_branch+'" class="gp_but"/>');
			
			var response_text = $('.branch_info_data').text();
			var response_url = host+'/catalog/firm/'+id_branch;
			
			insertVKButton($('#vk_but'+id_branch), response_url, name, response_text);
			insertFBButton($('#fb_but'+id_branch), response_url);
			insertTVButton($('#tw_but'+id_branch), response_url, name);
			insertGPButton($('#gp_but'+id_branch), response_url);
						
			$(obj).remove();
		});
	}
	else
	{
		$(obj).parent().prepend('<div id="vk_but'+id_branch+'" class="vk_but"/><div id="fb_but'+id_branch+'" class="fb_but"/><div id="tw_but'+id_branch+'" class="tw_but"/><div id="gp_but'+id_branch+'" class="gp_but"/>');
		
		var response_text = $('.branch_info_data').text();
		var response_url = host+'/catalog/firm/'+id_branch;
			
		insertVKButton($('#vk_but'+id_branch), response_url, name, response_text);
		insertFBButton($('#fb_but'+id_branch), response_url);
		insertTVButton($('#tw_but'+id_branch), response_url, name);
		insertGPButton($('#gp_but'+id_branch), response_url);
						
		$(obj).remove();
	}
	return false;
}

function makeLikes(id_responce,obj,link,title,nolj)
{
	if(!document_ready_flag)
	{
		$(document).ready(function()
		{
			$(obj).parent().prepend('<div id="vk_but'+id_responce+'" class="vk_but"/><div id="tw_but'+id_responce+'" class="tw_but"/><div id="gp_but'+id_responce+'" class="gp_but"/><div id="lj_but'+id_responce+'" class="lj_but"/><div id="fb_but'+id_responce+'" class="fb_but"/>');
			
			var response_text = $(obj).parent().parent().find('.response_li_text span,.text p').text();
			
			insertVKButton($('#vk_but'+id_responce), link, title, response_text);
			insertFBButton($('#fb_but'+id_responce), link);
			insertTVButton($('#tw_but'+id_responce), link, title);
			insertGPButton($('#gp_but'+id_responce), link);
			if (nolj==0)
			insertLJButton($('#lj_but'+id_responce), title, link, title, response_text);
						
			$(obj).remove();
		});
	}
	else
	{
		$(obj).parent().prepend('<div id="vk_but'+id_responce+'" class="vk_but"/><div id="tw_but'+id_responce+'" class="tw_but"/><div id="gp_but'+id_responce+'" class="gp_but"/><div id="lj_but'+id_responce+'" class="lj_but"/><div id="fb_but'+id_responce+'" class="fb_but"/>');
			
		var response_text = $(obj).parent().parent().find('.response_li_text span,.text p').text();
		
		insertVKButton($('#vk_but'+id_responce), link, title, response_text);
		insertFBButton($('#fb_but'+id_responce), link);
		insertTVButton($('#tw_but'+id_responce), link, title);
		insertGPButton($('#gp_but'+id_responce), link);
		if (nolj==0)
		insertLJButton($('#lj_but'+id_responce), title, link, title, response_text);
					
		$(obj).remove();
	}
	return false;
}

function toggle_my_profile(obj)
{
	var menu_my_profile = $('#menu_my_profile');
	
	if(obj.id=='my_profile')
	{
		obj.id='my_profile_active';
		$(obj).next().attr('src','/public/img/main_template/delta_black_up.gif');
		
		menu_my_profile.css('top', $(obj).offset().top + $(obj).innerHeight()/2-1);
		menu_my_profile.show();
	}
	else
	{
		obj.id='my_profile';
		$(obj).next().attr('src','/public/img/main_template/delta_black.gif');
		menu_my_profile.hide();
	}
}

function toggle_my_firm(obj)
{
	var menu_my_firm = $('#menu_my_firm');
	
	if(obj.id=='my_firm')
	{
		obj.id='my_firm_active';
		$(obj).next().attr('src','/public/img/main_template/delta_black_up.gif');
		
		menu_my_firm.css('top', $(obj).offset().top + $(obj).innerHeight()/2-1);
		menu_my_firm.show();
	}
	else
	{
		obj.id='my_firm';
		$(obj).next().attr('src','/public/img/main_template/delta_black.gif');
		menu_my_firm.hide();
	}
}

function toggleFirm(obj)
{
	$(obj).next().slideToggle('fast')
}

function redirect(url)
{
	document.location.href = url;
}
