$.fx.speeds._default = 300;
jQuery.expr[':'].Contains = function(a,i,m){
    return jQuery(a).text().toLowerCase().indexOf(m[3].toLowerCase())>=0;
}; 
$(document).ready(function(){	

	if ($("#slider").length) $("#slider").easySlider({controlsShow: false});
	if ($("#slider2").length) $("#slider2").easySlider({controlsShow: false});

	if ($( "#dialog:ui-dialog" ).length) $( "#dialog:ui-dialog" ).dialog( "destroy" );

    
    try{
    	$( "#delDialog" ).dialog({
	    	modal: true,
		    autoOpen:false,
    		width: 400,
	    	dialogClass:'alert'
	    });

	    $( "#div_confirm" ).dialog({
		    modal: true,
		    autoOpen:false,
		    width: 370,
		    buttons: {
			    "Сохранить": function() {
				    submit_confirm();
				    $( this ).dialog( "close" );
			    },
			    "Отменить": function() {
				    $( this ).dialog( "close" );
			    }
		    }
	    });
	    
	    $( "#div_otzyv" ).dialog({
		    modal: true,
		    autoOpen:false,
		    width: 370,
		    buttons: {
			    "Сохранить": function() {
				    submit_otzyv();
				    $( this ).dialog( "close" );
			    },
			    "Отменить": function() {
				    $( this ).dialog( "close" );
			    }
		    }
	    });
	}
	catch(exception){
	}
	
	$('input#mySearch').keyup(function() {
		filter = $(this).val();
		$('div.more2').each(function(){
			obj=$(this).find('div.blue_style:first:Contains("' + filter + '")');
			if (obj.length>0) $(this).fadeIn(400);
			else $(this).fadeOut(400);
		});
	});		
});


function delDisp(name,str){
	$( "#delDialog" ).dialog({
		buttons: {
			"Да": function() {
				$( this ).dialog( "close" );
				if (str.indexOf('document.')>-1) eval(str);
				else document.location = str;
			},
			"Нет": function() {
				$( this ).dialog( "close" );
			}
		}
	});
	$('#delDialog').text('Вы хотите удалить '+name);
	//$('#delDialog').attr('url',str);
	$('#delDialog').dialog('open');
//	if (confirm("Вы хотите удалить "+name+"?")){
//                document.location = str;
//        }
}

function conDisp(name,str,notUrl){
	$( "#delDialog" ).dialog({
		title:'Внимание',
		buttons: {
			"Да": function() {
				$( this ).dialog( "close" );
				if (notUrl==1) eval(str);
				else document.location = str;
			},
			"Нет": function() {
				$( this ).dialog( "close" );
			}
		}
	});
	$('#delDialog').text('Вы хотите '+name);
	$('#delDialog').dialog('open');

/*
	if (confirm("Вы хотите "+name+"?")){
                document.location = str;
        }
 */
}

function show_registration(){
	$( "#delDialog" ).dialog({
		title:'Ошибка',
		modal: false,
		buttons: {
			"Да": function() {
				$( this ).dialog( "close" );
				document.location = $(this).attr('url');
			},
			"Нет": function() {
				$( this ).dialog( "close" );
			}
		}
	});
	$('#delDialog').text('Чтобы использовать данную возможность необходимо зарегистрироваться или авторизироваться. Перейти на страницу регистрации?');
	$('#delDialog').attr('url','registration.php');
	$('#delDialog').dialog('open');

/*
 	if (confirm('Чтобы использовать данную возможность необходимо зарегистрироваться или авторизироваться. Перейти на страницу регистрации?')){
	    document.location='registration.php'
	}
	*/	
}

function add_friend_dialog(id,name){
	$( "#delDialog" ).dialog({
		title:'Добавление в друзья',
		modal: false,
		buttons: {
			"Да": function() {
				$( this ).dialog( "close" );
				add_friend(id);
			},
			"Нет": function() {
				$( this ).dialog( "close" );
			}
		}
	});
	$('#delDialog').text('Вы действительно хотите добавить в друзья '+name+'?');
	$('#delDialog').dialog('open');

/*
 	if (confirm('Чтобы использовать данную возможность необходимо зарегистрироваться или авторизироваться. Перейти на страницу регистрации?')){
	    document.location='registration.php'
	}
	*/	
}

function alert_href_dialog(str,alert_hrefs){
	$( "#delDialog" ).dialog({
		title:'Ссылка на другой сайт',
		modal: true,
		width: 400,
		buttons: {
			"Перейти": function() {
				$( this ).dialog( "close" );
				if ($('#delDialog').attr('alert_hrefs')=='0') alert_href_set();
				window.open($(this).attr('url'));
			},
			"Закрыть": function() {
				if ($('#delDialog').attr('alert_hrefs')=='0') alert_href_set();
				$( this ).dialog( "close" );
			}
		}
	});
	$('#delDialog').html('Вы покидаете сайт Clubparadise.ru по внешней ссылке, предоставленной одним из участников.<br>'+
				'Администрация Clubparadise.ru не несет ответственности за содержимое сайта и настоятельно рекомендует не указывать никаких своих данных, имеющих отношение к Clubparadise.ru (особенно e-mail, пароль и cookies), на сторонних сайтах.'+
	(alert_hrefs==1?'<p><input type="checkbox" onclick="$(\'#delDialog\').attr(\'alert_hrefs\',0)">Больше не показывать это предупреждение</p>':''));
	$('#delDialog').attr('url',str);
	$('#delDialog').attr('alert_hrefs',alert_hrefs);
	$('#delDialog').dialog('open');

/*
 	if (confirm('Чтобы использовать данную возможность необходимо зарегистрироваться или авторизироваться. Перейти на страницу регистрации?')){
	    document.location='registration.php'
	}
	*/	
}

function alert_href_set() {
        JsHttpRequest.query(
            '/?act=alert_href', // backend
            {
                'str': 0  
            },
            function(result, errors) {
                if (errors) my_alert(errors); 
                //if (result["ok"]) my_alert(result["ok"]);
            },
            false  // do not disable caching
        );
}


function my_alert(str)
{
	$( "#delDialog" ).dialog({
		title:'Внимание',
		modal: true,
		buttons: {
			"Ok": function() {
				$( this ).dialog( "close" );
			}
		}
	});
	$('#delDialog').text(str);
	$('#delDialog').dialog('open');

}

function show_action_invite()
{
	my_alert('Чтобы использовать данную возможность необходимо вступить в сообщество.');
}

function get_city(sel,a) {
    $('#city_s, #city_top').html('Загрузка... &nbsp;&nbsp;&nbsp;');
    JsHttpRequest.query(
	'/registration.php?act=get_city&id='+sel+'&char='+a, // backend
	{
	    'str': sel  
	},
	function(result, errors) {
	    if (errors) my_alert(errors); 
	    $("#city_s").html('<select name="city_id" style="width:150px" onchange="get_metro(this.value,\'\');">'+result["str"]+'</select>');
	    $("#city_top").html('<select name="setcid" style="width:150px">'+result["str"]+'</select>');
	    //get_metro(document.reg.city_id.value,'e');
	},
	false  // do not disable caching
    );
}

function get_metro(sel,a) {
    $('#metro_s').html('Загрузка... &nbsp;&nbsp;&nbsp;');
    JsHttpRequest.query(
	'/registration.php?act=get_metro&id='+sel+'&char='+a, // backend
	{
	    'str': sel  
	},
	function(result, errors) {
	    if (errors) my_alert(errors); 
	    $("metro_s").html('<select name="metro_id" style="width:150px">'+result["str"]+'</select>');
	},
	false  // do not disable caching
    );
}

function add_friend(id){
    JsHttpRequest.query(
	'/index.php?act=add_friend&id='+id, // backend
	{
	    'str': id  
	},
	function(result, errors) {
	    if (errors) my_alert(errors); 
	    if (result) my_alert(result['str']);
	    //if (!errors) document.getElementById("friend"+id).style.display="none";
	},
	true  // do not disable caching
    );
}

function KeyPress(e)
{
	var kk = navigator.appName == 'Netscape' ? e.which : e.keyCode;
	if (kk == 13)
	{
		document.freg.submit();
		return false;
	}		
	return true;
}

function hide_text(num,show,img){
	var divid = document.getElementById('hide_div'+num);
	var pid = document.getElementById('img'+num);
	if (divid)
//	if(divid.style.display=='block' && !show){
	if($(divid).is(':visible') && !show){
		if (pid){
		if (img) pid.src='/images/ass_1.jpg';
		else pid.src='/images/plus.jpg';
		}
		$(divid).slideUp();//.style.display='none';
	}
	else {
		if (pid)
		if (img) pid.src='/images/ass_2.jpg';
		else pid.src='/images/minus.jpg';
		$(divid).slideDown();//.style.display='block';
	}
}

  var height=0;
  var width=0;

  if( typeof( window.innerWidth ) == 'number' ) {
    //Non-IE
    width = window.innerWidth;
    height = window.innerHeight;
  } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
    //IE 6+ in 'standards compliant mode'
    width = document.documentElement.clientWidth;
    height = document.documentElement.clientHeight;
  } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
    //IE 4 compatible
    width = document.body.clientWidth;
    height = document.body.clientHeight;
  }

function getScrollY() 
{
        scrollY = 0;    
        if (typeof window.pageYOffset == "number") {
                scrollY = window.pageYOffset;
        } else if (document.documentElement && document.documentElement.scrollTop) {
                scrollY = document.documentElement.scrollTop;
        }  else if (document.body && document.body.scrollTop) {
                scrollY = document.body.scrollTop; 
        } else if (window.scrollY) {
                scrollY = window.scrollY;
        }
        return parseInt(scrollY);
}

var soundEnable = 1;


function playSound(path) {
	var sound = '/images/'+path+'.swf';
	if (soundEnable) {
		document.getElementById('soundContainer').innerHTML = '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"'+
		'codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,28,0">'+
		'<param name="movie" value="'+sound+'"><param name="quality" value="high">'+
		'<embed src="'+sound+'" quality="high" pluginspage="http://www.adobe.com/shockwave/download/download.cgi?P1_Prod_Version=ShockwaveFlash" '+
		'type="application/x-shockwave-flash"></embed></object>';
	}
}

function enableSound() {
	if (soundEnable == 0) {
		soundEnable = 1;
	}
}

function disableSound() {
	if (soundEnable == 1) {
		soundEnable = 0;
	}
}

function toggleSound() {
	if (soundEnable) {
		disableSound();
	} else {
		enableSound();
	}
}

function checkGroupEvents() 
{ 
        JsHttpRequest.query(
            '/groups.php?act=chkge',
            {
                'ok': 0
            },
            function(result, errors){
                if (result["err"]){
			playSound('sound1');
			my_alert(result["err"]);
		}
		    //if (result["ok"]){ }
            },
            true  // do not disable caching
        );
        setTimeout("checkGroupEvents();", 300000); 
} 

function init_page(){
    checkGroupEvents();
}

function PopupPic(sPicURL) {
    window.open('/popup.php?s='+sPicURL, "", "resizable=1,HEIGHT=20,WIDTH=20");
//myWin=open("","","top=200,left=-200,width=10,height=10");
//myWin.document.write("<html><head><title></title></head><body onload=\"window.print(); window.close();\"><img src=\"ui/?s="+sPicURL+"=10\" /></body></html>");
}

function addslashes(str) {
str=str.replace(/\\/g,'\\\\');
str=str.replace(/\'/g,'\\\'');
str=str.replace(/\"/g,'\\"');
str=str.replace(/\0/g,'\\0');
str=str.replace(/\n/g,'\\n');
str=str.replace(/\r/g,'');
str=str.replace(/<br>/g,'\\n');
return str;
}

function show_form(show,oDiv2,id,oSF,path){
        oDiv1=document.getElementById("div_confirm_big");
        if (oDiv1){
	    oDiv2.style.left=(parseInt(width)-parseInt(oDiv2.style.width))/2+"px";
	    oDiv2.style.top=getScrollY()+height/2-50+"px";
	    //alert(getScrollY()+' - l:'+oDiv2.style.left+' - t:'+oDiv2.style.top);
	    if (show){
		$(oDiv1).fadeIn();//style.display='block';
		$(oDiv2).fadeIn();//.style.display='block';
		if (oSF && path)
		if (id){
		    oSF.innerHTML='<a href="/ui/?s='+path+'=10" target=_blank title="Посмотреть изображение">'+
		    '<img src="/ui/?s='+path+'=4" alt="Посмотреть изображение" /></a><br />';
		} else
		    oSF.innerHTML='';
	    } else {
		$(oDiv2).fadeOut();//.style.display='none';
		$(oDiv1).fadeOut();//.style.display='none';
	    }
	}	
}

function setOpacity()
{
	el_a = document.getElementById("div_confirm_big");
	
	el_a.style.filter="alpha(opacity:50)";
	el_a.style.KHTMLOpacity="0.50";
	el_a.style.MozOpacity="0.50";
	el_a.style.opacity="0.50";
        //el_a.style.filter="progid:DXImageTransform.Microsoft.Alpha(opacity=50)";
}

function show_confirm(div,show,id,from_id,type,mess){
    if (div=='1'){
	oDiv=document.getElementById('div_confirm');
	if (id) document.fmch.id.value=id;
	if (from_id) document.fmch.group_id.value=from_id;
    }
    if (div=='2'){
	oDiv=document.getElementById('div_otzyv');
	if (id) document.fotz.id.value=id;
	if (from_id) document.fotz.from_id.value=from_id;
	if (type) document.fotz.act1.value=type;
	if (mess) document.fotz.comments.value=mess;
	else document.fotz.comments.value='';
    }

	if (oDiv) $(oDiv).dialog('open');
/*
oDiv1=document.getElementById("div_confirm_big");
if (oDiv){
    oDiv.style.left=(parseInt(width)-parseInt(oDiv.style.width))/2+"px";
    oDiv.style.top=getScrollY()+(parseInt(+height)-parseInt(oDiv.style.height)-100)/2+"px";
    if (show){
	    $(oDiv1).fadeIn();//style.display='block';
	    $(oDiv).fadeIn();//.style.display='block';
    } else {
	    $(oDiv).fadeOut();//.style.display='none';
	    $(oDiv1).fadeOut();//.style.display='none';
    }
}
*/
}

function submit_confirm(div){ 
        JsHttpRequest.query(
            '/index.php?act=post_mychoose&comments='+encodeURIComponent(document.fmch.comments.value)+
	    '&id='+document.fmch.id.value,
            {
                'ok': 0
            },
            function(result, errors){
                if (result["err"]) my_alert(result["err"]);
		if (result["ok"]==1){ show_confirm('1',0);}
            },
            true  // do not disable caching
        );
        
}

function submit_otzyv(){ 
    // Create new JsHttpRequest object.
    var req = new JsHttpRequest(); 
    // Code automatically called on load finishing.
    req.onreadystatechange = function() {
        if (req.readyState == 4) {
                if (req.responseJS.err) my_alert(req.responseJS.err);
		if (req.responseJS.ok==1){ show_confirm('2',0);}
		if (req.responseJS.refresh==1){ document.location.reload();}
		if (req.responseText) my_alert(req.responseText);
        }
    }
    req.caching = false; 
    req.loader = 'form'; 
    // Prepare request object (automatically choose GET or POST).
    req.open(null, '/index.php', true);
    // Send data to backend.

    req.send(
	{ act:'post_otzyv',
	comments:document.fotz.comments.value,
	id:document.fotz.id.value,
	from_id:document.fotz.from_id.value,
	act1:document.fotz.act1.value}
    );
  
}

var group_id=0;
function set_rayting(id){
	$('#sp_r1').html('Загрузка...');
	$('#sp_r2').html('Загрузка...');
	//alert('/user_photos.php?act=set_rayting&group_id='+group_id+'&user_id='+user_id+'&id='+pic_id+'&price='+id);
	JsHttpRequest.query(
        '/user_photos.php?act=set_rayting&group_id='+group_id+'&user_id='+user_id+'&id='+pic_id+'&price='+id, // backend
        {
            'str': id  
        },
        function(result, errors) {
	        if (errors) alert(errors);
		spr1=document.getElementById("sp_r1");
		if (spr1){
		if (result['r2']) spr1.innerHTML='Рейтинг фото: <span>'+result['r2']+'</span>';
		else spr1.innerHTML='Рейтинг фото: <span>0</span>';
		}
		spr1=document.getElementById("sp_r2");
		if (spr1){
		if (result['r2']) spr1.innerHTML='Рейтинг фото: <span>'+result['r2']+'</span>';
		else spr1.innerHTML='Рейтинг фото: <span>0</span>';
		}
		spr1=document.getElementById("div_voited");
		if (spr1)
		if (result['voited']==1){
			spr1.innerHTML='Ваш голос учтен.';
			$("#m").fadeOut();
			$("#m1").fadeIn();
		} else {
			spr1.innerHTML='';
			$("#m1").fadeOut();
			$("#m").fadeIn();
		}
		if (result['voite']==1) my_alert('Ваш голос учтен');
		if (result['r1']) $('#howVoted').html('<a href="/photo_voted.php?group_id='+group_id+'&user_id='+user_id+'&id='+pic_id+'">'+result['r1']+'</a>');
		
        },
        true  // do not disable caching
    );
	return false;
}

function odserve_swf_alert(string) {
	alert(string);
}
function odserve_swf_pic_uploader_rewrite_param(param_name,param_val) {
	odserve_swf_Movie("ODServePictureUploader").updateParameter(param_name,param_val);
}
function odserve_swf_trace(string) {
	document.getElementById("trace-area").innerHTML += string + '<br />';
}
function odserve_swf_Movie(movieName) {
	if (navigator.appName.indexOf("Microsoft") != -1) {
		return window[movieName]
	} else {      return document[movieName]}
}

function floader(v_upload_url,v_upload_redirect,v_user_id,v_cat,v_group_id){
	var flashvars = {

		upload_url: v_upload_url,
		upload_redirect: v_upload_redirect,

		//general photo
		max_size_after_resizing: "800",
		byte_arrays_name: "flimages",	//name for POST-variable includ file for uploading
		//additional photo
		//plural_resize: "200;100", //0 - disable
		//plural_resize: "200", //0 - disable
		
		pictures_on_line: "5",
		photos_count: "20",
		max_pictures: "20", //0 - unlimit

		preview_size_px: "110",

		pic_horizontal_outline_px: "10",
		pic_vertical_outline_px: "10",

		horizontal_outline_px: "20",
		vertical_outline_px: "104",

		slide_panel_y_pos_before_hide: "73",
		slide_panel_y_pos_after_hide: "102",
		scroll_vertical_outline_px: "104",
		scroll_horizontalr_outline_px: "14",
		scroll_vertical_down_outline_px: "24",

		pic_glowframe_enable: "1", //1 or 0
		pic_glowframe_color: "0xD4D4D4",
		pic_glowframe_width_px: "5",
		pic_glowframe_height_px: "5",
		pic_glowframe_alpha: "1",
		pic_glowframe_anim_sec: "0.75",

		/* WARNING: do not edit this jpeg parameters,if
		   you dont know what thay means.
		 */
		jpeg_encode_param_1: "3",
		jpeg_encode_param_2: "2",
		jpeg_quality: "95",
		
		lang_button_add: 'Выбрать',
		lang_button_del: "Удалить",
		lang_button_upload: "Загрузить",
		lang_zero_upload_error: "Не выбрано фотографий",
		lang_loadingbar_caption: "Загрузка",
		lang_picture_limit_error: "Превышен лимит фотографий",
		lang_picture_server_answer_upload_error: "Не удалось загрузить фотографии.",
		//по завершению загрузки будет подтверждение
		lang_uploadcomplete_title: "загрузка завершена.",//заголовок для подтверждения для повторной загрузки
		lang_uploadcomplete_message: "Вы хотите загрузить еще фотографии??!",

		lang_uploadcomplete_title_error: "загрузка завершена с ошибками.",//заголовок для подтверждения для повторной загрузки с ошибкой
		lang_uploadcomplete_message_error: "Вы хотите загрузить еще фотографии?",

		lang_confirm_yes: "Да",
		lang_confirm_no: "Нет",
		
		/* WARNING:do not use variable's name like:
		 "_http_GET_ID"
		 "_http_GET_size"
	 */
		//данные уникальные для каждого пользователя
		'_http_GET_group_id': v_group_id,
		'_http_GET_user_id': v_user_id,
		'_http_GET_cat': v_cat,
		'_http_GET_USER_UNIQUECODE': "asd123",
		'_http_POST_USER_INFO': "asdcbvb"

	};
	var params = {
		allowScriptAccess: 'always',
		bgcolor: '#F8F8F8'
	};

	var attributes = {
		id: "ODServePictureUploader",
		name: "ODServePictureUploader"
	};

	attributes.id = "ODServe_FU";
	swfobject.embedSWF("/floader/_photoloader.odserve.swf", "AlternativeContent", "648", "486", "10.0.32", 
	                   "/floader/expressInstall.swf", flashvars, params, attributes);    
}

function vk_login() {
	VK.Auth.login(function(r) {
	    if (r.session) {
		JsHttpRequest.query(
		'/index.php?act=authVK&id='+r.session.mid,
		{
		    'str': 1
		},
		function(result, errors) {
			if (errors) alert(errors);
			if (result['str']){
				if (result['str']=='notauth') my_alert('Вы не авторизованы в vkontakte');
				else document.location=result['str'];
			}
		},
		true  // do not disable caching
		);
	    } else {
		// TODO: write error handler
	    }
	}, 2);
}

function vk_login_reg() {
	VK.Auth.getLoginStatus(function(r) {
	    if (r.session) {
		JsHttpRequest.query(
		'/index.php?act=authVK_reg&id='+r.session.mid,
		{
		    'str': 1
		},
		function(result, errors) {
			if (errors) alert(errors);
			if (result['str']){
				if (result['str']){
				    $('td#vk_reg').html(result['str']+' <a href="" onclick="conDisp(\'привязать аккаунт '+result['str']+'?\',\'/user_about.php?act=addvk\'); return false;">Привязать</a>');
				} else {
				    $('td#vk_reg').html('<script type="text/javascript"> VK.UI.button(\'vk_auth1\');</script><div id="vk_auth1" onclick="vk_login1(); return false;">ВКонтакте</div>');
				}
			}
		},
		true  // do not disable caching
		);
	    } else {
		$('td#vk_reg').html('<script type="text/javascript"> VK.UI.button(\'vk_auth1\');</script><div id="vk_auth1" onclick="vk_login1(); return false;">ВКонтакте</div>');
	    }
	});
}

function vk_login1() {
	VK.Auth.login(function(r) {
	    if (r.session) {
		document.location='/user_about.php';
	    } else {
		// TODO: write error handler
	    }
	}, 2);
}

/*
var snow_intensive=700; 
var snow_speed=20000; 
var snow_src=new Array('sneg1.gif','sneg2.gif','sneg3.gif'); 

function snow_start() { 
	snow_id=1;
	setInterval(function() { 
		snow_y=$(window).height()-20+$(document).scrollTop(); 
		snow_x=Math.random()*document.body.offsetWidth-100; 
		snow_img=(snow_src instanceof Array ? snow_src[Math.floor(Math.random()*snow_src.length)] : snow_src); 
		snow_elem='<img class="png" id="snow'+snow_id+'" style="position:absolute; left:'+snow_x+'px; top:'+($(document).scrollTop()-30)+'px;z-index:10000" src="/images/sneg/'+snow_img+'">';
		$('body').append(snow_elem);
		snow_move(snow_id); 
		snow_id++; 
	},snow_intensive);
} 

function snow_move(id) { 
	$('#snow'+id).animate({top:snow_y,left:"+="+Math.random()*100},snow_speed+Math.random()*snow_speed/2,function() { 
		$(this).empty().remove(); });
} 

*/
