$(document).ready(function(){		
	/* js is work */
	$("#gatar").removeClass("no_js");

	/* capthca */ 
	$("#captcha").click(function(){
		$(this).attr("src", '/service/captcha/captcha.php?i='+getRandom());
		return false;						 
	});
	
	/* search example */
	$("#poisk").click(function(){
		var napr = $(this).html();
		$("#searchinp").attr("value", napr ).focus();
		return false;
	});
	
	$('.spoiler').click(function(){
		$(this).fadeslide();
		return false;
	});
	
	/* city list */
	$("#cityid").click(function(){
		if ($.browser.msie && $.browser.version.substr(0,3)=="6.0") {	
			return true;
		} else {	
			if ( $(this).data('obtained') == true ) {
				$("#citylist").show();
			} else {
				$.ajax({
					type: 'post',
					url: '/ajax.php',
					data: 'path='+escape(document.location.href)+'&acttype=citys',
					dataType: 'xml',
					success: function(xml){
						parsercode(xml);
						start_functions();
						},
					timeout: 6000   
				});
			}
		return false;
		}
	});
	
	jfunctions = {
	
		add_item: function(){
			jfunctions['datepicker']();				
		},
		
		datepicker: function() {
			// datepicker  
			$("#mydate").datetimepicker({ dateFormat: 'dd.mm.yy'}).click(function(){
				$(this).prev().children(":first").attr("checked", "checked");
			});
			$("#step-au").bind('change', function() {
				if ($(this).attr("value") == 1 ) {
					$(this).parent().parent().next().show();
				} else {
					$(this).parent().parent().next().hide();
				}
			});
		},
		
		item_info: function() {
			/* WATCH */
			$(".vozm").click(function(){
				var data = $(this).attr("href");
				var clicked = $(this);
				$.ajax({
					url: '/ajax.php?view=watch',
					type: 'post',
					data: 'id='+data+'&acttype=watch',
					dataType: 'xml',
					success: function(xml){
						parsercode(xml);
						if ( html[0] =='youwatched' ) {
							$(clicked).html(text[1]).attr("href", data.replace( /watch/, 'nowatch' )).next().fadeOut(30).fadeIn(300);
						} else if ( html[0] =='younotwatched') {
							$(clicked).html(text[0]).attr("href", data.replace( /nowatch/, 'watch' )).next().hide(); 		   
						}
					},
					timeout: 6000
				});
			
				return false;
			});
				
			// izmenit photo tovara 
			$(".reimg").click(function(){
				$('#loader').show();
				$(".vibminiimg").removeClass("vibminiimg").addClass("obminiimg");
				$(this).removeClass("obminiimg").addClass("vibminiimg");
				var filename = $(this).children().attr("src");
				filename = filename.match("(?:[0-9a-z]{32}.(?:png|jpg|gif))");
				var pathimg = $('#osnfoto').attr("src");
				pathimg = pathimg.substr(0,(pathimg.length-36))+filename;
				$('#osnfoto').attr("src", pathimg).load(function(){
					$('#loader').hide();
				});
				return false;
			});
		},
		
		item_edit: function(){
			// sale type change
			$("#fs").bind('change', function(){
				var i = $(this).attr("value");
				if ( i == 1 ) {
					$("#fsp").show().next().show();
				} else if (i == 2) {
					$("#fsp").show().next().hide();
				} else if (i == 3) {
					$("#fsp").hide().next().show();
				}
			});
			jfunctions['datepicker']();	
		},
		
		activity: function() {
			// actiob in activity 
			$(".actmenu").toggle(
				function(){
					$(this).removeClass("pad1").addClass("pad2").children().css("background-position","right top").parent().next().show();	
					$(this).children().parent().parent().addClass("podsk");
					return false;
				},function(){
					$(this).removeClass("pad2").addClass("pad1").children().css("background-position","left top").parent().next().hide();
					$(this).children().parent().parent().removeClass("podsk");
					return false;
				}
			);
		},
		
		myworld: function() {
			
			// change passwoed 
			$('#repassform').submit(function(){
				$(this).children().children('li.errorka').hide();
				newpass = $('#new_pass').attr("value");	
				newpass_a = $('#pass_a').attr("value");	
				var err = false;
				if (newpass!=newpass_a) {
					$(this).children().children(':last').prev().fadeIn();
					err = true;
				}
				if (newpass.length < 8) {
					$(this).children().children(':last').prev().prev().fadeIn();
					err = true;
				}
				if (newpass.length > 51 ) {
					$(this).children().children(':last').prev().prev().prev().fadeIn();
					err = true;
				}
				if(err) return false; 
				var data = $(this).serialize();
				data = data+'&acttype=change_pass';
				$.ajax({
					url: '/ajax.php',
					type: 'post',
					data: data,
					dataType: 'xml',
					success: function(xml){
						parsercode(xml);
						start_functions();
					},
					timeout: 6000
				});
				return false;
			});
			
			// change email 
			$('#remailform').submit(function(){
				$(this).children().children('li.errorka').hide();
				data = $(this).serialize();
				newpass = $('#newmail').attr("value");	
				if ( !newpass.match( /\w+@\w+\.[a-z]{2,3}/ ) ) {
					$('#newmail').parent().next().fadeIn();	
					return false;
				}
				$.ajax({
					url: '/ajax.php',
					type: 'post',
					data: data+'&acttype=change_email',
					dataType: 'xml',
					success: function(xml){
						parsercode(xml);
						start_functions();
					},
					timeout: 6000 
				});
				return false;
			});
			
			// ajax load 
			$('#editcontactinfo').live('click', function(){
				$(this).attr('href','#!/myworld/?v=editcontactinfo');
				$('#righttd').loadform('personalinfo');
			});
			$('#myavatar').live('click', function(){
				$(this).attr('href','#!/myworld/?v=myavatar');
				$('#righttd').loadform('myavatar');
			});
			$('#myprivacy').live('click', function(){
				$(this).attr('href','#!/myworld/?v=myprivacy');
				$('#righttd').loadform('privacy');
			});
			
			// deleting avatar
			$('#deleteava').live('click', function(){
				clicked = $(this);
				$.ajax({
					url: "/ajax.php",
					data: { 'acttype' : 'myavatar_del' },
					type: "post",
					dataType: "xml",
					success: function(xml){
						parsercode(xml);	
						start_functions();
					},
					timeout: 6000
				});		
				return false;		
			});
			
			// privacy configuration
			$("#privacy .btn").live('click', function() {
				if ($(this).hasClass("bwhite")&&!$(this).hasClass("cancel")){
					$(this).removeClass("bwhite").parent().children(".bblue").removeClass("bblue").addClass("bwhite").end().end().addClass("bblue");
					id = $(this).attr("id");
					found = id.match(/[_a-z]+([0-9]+)/);
					$(this).parent().children(":last").attr("value", found[1]);
					return false;
				} else if ($(this).hasClass("bblue")) {
					return false;
				}
			});
		
			// feedback rate
			$(".frate a").live('click', function(){
				if ( $(this).hasClass('bwhite') ) {
					var rate = 1; var cl = 'fneitral';
				} else if ( $(this).hasClass('bred') ) {
					var rate = 0; var cl = 'fbad';
				} else if ( $(this).hasClass('bgreen') ) {
					var rate = 2; var cl = 'frapture';
				}
				if ( $(this).parent().parent().parent().parent().hasClass(cl) ) return false;
				$(this).parent().parent().parent().parent().removeClass('fneitral frapture fbad').addClass(cl);
				$(this).parent().children(':last').attr('value', rate);
				return false;
			});
			
			// save feedback
			$(".sendfeed").saveform('save_feedback');
		},
		
		mymessages: function() {
			// show mess form 
			$(".showmessform").click(function(){
				$(this).next().show().prev().hide();
				return false;
			});
			
			// show answer
			$(".anslink").click(function(){
				$(this).hide().parent().parent().removeClass('rb').addClass('rb3').next().show();
				return false;
			});
				
			// close answer form 
			$(".close3").click(function(){
				$(this).parent().parent().parent().parent().parent().parent().parent().parent().hide().prev().removeClass('rb3').addClass('rb').children(":last").children(":first").show();
				return false;
			});
		},
		
		photoedit: function() {
			$('#images').click(function(e) {
				clicked = $(e.target);	
				var send = false;
				// delete
				if ($(clicked).hasClass('deletethisitem') ) {
					idf = $(clicked).parent().attr("id");
					type = 'delete';
					send = true;
				}
				// make a main
				if ($(clicked).hasClass('makemeamain') ) {
					idf = $(clicked).parent().attr("id");
					type = 'makeamain';
					send = true;
				}
				
				if (send) {
					$.ajax({
						url: '/ajax.php',
						type: 'post',
						beforeSend: function(){
							$(clicked).parent().children(":last").show();
						},
						data: 'idf='+idf+'&acttype=photo&type='+type,
						dataType: 'xml',
						success: function(xml){
							parsercode(xml);
							start_functions();
						},
						complete: function(){
							$(clicked).parent().children(":last").hide();
						},
						timeout: 6000
					}); // close ajax
					return false;
				} // close if
				
			}); // close function

			$("#loadimage").submit(function(){
				ajaxFileUpload('addimageinitem', tid);
				return false;
			}); // close submit
		}
	}
	
	// start functions
	if ( typeof( jfunctions[thispage]) == 'function' ) {
		jfunctions[thispage]();			
	}
	
});

function prederr(errmess){
	if ( errmess instanceof Array ) {
		if (showpredmess>0) {
			$("#pred").remove();
		}
		err = '';
		for(var i=0; i<errmess.length; i++) {
			err += '<p class="predmess"><span class="info">.</span>'+errmess[i]+'</p>';				
		}
		showpredmess+=i;
		$("#osn").prepend('<div id="pred" style="opacity: 0;">'+err+'</div>').children(':first').animate({opacity: 1});
	} else {
		if (showpredmess==0) {
			$("#osn").prepend('<div id="pred"><p class="predmess"><span class="info">.</span>'+errmess+'</p></div>');
		} else {
			$("#pred > .predmess:first").remove();
			$("#pred").append('<p class="predmess" style="opacity: 0;"><span class="info">.</span>'+errmess+'</p>').children(':last').animate({opacity: 1});
		}
		showpredmess++;
	}
}

jQuery.fn.fadeslide = function(){
	$(this).children(':first').toggleClass('viewed').end().next().animate({height: 'toggle'}, 'fast');		
};

var functions = {

	myavatar: function() {
		$("#righttd .cancel").click(function(){
			$(this).attr('href','#!/myworld/?v=info');
			$("#righttd").loadform("myworld");
		});
		$("#loadimage").submit(function(){
			ajaxFileUpload('myavatar_new', 'undefined');
			return false;
		});
	},
	
	myavatar_loaded: function( agrs ) {
		upath = agrs.upath;
		path = agrs.path;
		var r = getRandom();
		$("#imagetoupload").attr("value","");
		$("#mainava").attr("src", path+"l"+upath+"?r="+r).load().parent().next().next().next().show();
		$("#miniava").attr("src",path+"m"+upath+"?r="+r).load().parent().parent().parent().next().children().children().children().attr("src",path+"s"+upath+"?r="+r);
		$("#avatr").children(":first").attr( "src", path+"s"+upath+"?r="+r );
		$("#avtrimg").children(":first").attr( "src", path+"m"+upath+"?r="+r );
	},
	
    myavatar_deleted: function( agrs ) {
		path = agrs.path;
        $("#mainava").attr("src", path+"l/noavatar.jpg").load();
		$("#miniava").attr("src",path+"m/noavatar.jpg").load().parent().parent().parent().next().children().children().children().attr("src",path+"s/noavatar.jpg");
		$("#avatr").children(":first").attr( "src", path+"s/noavatar.jpg" );
		$("#avtrimg").children(":first").attr( "src", path+"m/noavatar.jpg" );
		$(clicked).hide();
    },
	
	personalinfo: function() {
		$("#righttd .cancel").click(function(){
			$(this).attr('href','#!/myworld/?v=info');
			$("#righttd").loadform("myworld");
		});
		$("#personalinfo").saveform('savemyinfo');
	},
	
	privacy: function() {
		$(".cancel").click(function(){
			$(this).attr('href','#!/myworld/?v=info');
			$("#righttd").loadform("myworld");
		});
		$("#saveprivacy").saveform('save_privacy');
	},
	
	feedback_sended: function() {
		k = $(form).parent().parent();
		$(form).parent().slideUp( 'normal', function(){$(this).remove();});
		if ( typeof(html[1]) != 'undefined' ) {
			$(k).append(html[1]);	
		}
		if ( $(k).html() == '' ) {
			$(k).parent().remove();
		}
		$("#feedfrom").prepend(html[0]).children(':first').css("display", 'none').fadeIn('slow');	
	},
	
	change_pass_success: function() {
		$('#repassform').children().children(':first').next().children().attr("value", '');	
		$('#new_pass').attr("value", '');	
		$('#pass_a').attr("value", '');	
		$("#repassform").parent().prev().fadeslide();
	},
	
	change_email_succsess: function() {
		$('#remailform').parent().prev().fadeslide();
	},
	
	city_list: function() {
		$("#page").before(html[0]);
		$("#citylist .mycity").click(function(){
			$.cookie(cookiepref+'city', $(this).attr("id").substr(3), { expires: 14, path: '/' });	
			return true;
		});
		$("#cityid").data('obtained', true );
		$("#clcitlist").click(function(){
			$(this).parent().parent().hide();
			return false;
		});
	},
	
	photo_deleted: function( agrs ) {
		osnfoto = agrs.osnfoto;
		newosn = agrs.newosn;
		$(clicked).parent().animate({"width": "0",opacity: "hide"}, "fast", "linear", function(){
			$(clicked).remove();
		});
		
		if (osnfoto!='0') {
			var height = $("#phto").height() + 25;
			$("#phto").css('height',height).html(html[0]);			
		}
		if (newosn!='0') {
			$("#idf-"+newosn).children(":first").next().hide();
		}
	},
	
	main_image_established: function() {
		var height = $("#phto").height() + 25;
		$("#phto").css('height',height).html(html[0]);
		$("#images .makemeamain").show();
		$(clicked).hide();
	},
	
	image_added: function() {
		$("#images").append(html[0]);
		if ( typeof(html[1]) != 'undefined' ) $("#phto").html(html[1]);
		$("#images").children(":last").fadeOut(10).fadeIn(500);
	},
	
	showbox: function( agrs ) {
		var header = agrs.header; 
		if ( typeof( agrs.bottons ) != 'undefined') {
			var closebtn = '';
			var bottons = ''+agrs.bottons+'</div>'; 
		} else {
			var bottons = '';
			var closebtn = '<a href="#" class="cl fr">X</a>';
		}
		var mess = '<div class="box"><div class="box-container"><div class="box-dialog"><div class="box-content"><h2>'+closebtn+header
		+'</h2><div class="box-inner">'+html[0]+'</div>'+bottons+'</div></div></div></div>';
		var bheight = $("#gatar").prepend(mess).children(":first").children().height();
		if(window.innerHeight){
			var gheight = window.innerHeight;
			var scr = window.scrollY;
		} else if (document.documentElement && document.documentElement.clientHeight) {
			var gheight = document.documentElement.clientHeight;
			var scr = document.documentElement.scrollTop;
		} else if (document.body && document.body.clientHeight){
			var gheight = document.body.clientHeight;
			var scr = 0;
		}
		if ( gheight - 360 < bheight ) {
			gheight -= 400;
			if ( gheight < 400 ) gheight = 400;
			$("#gatar .box-inner").css({
				height: gheight
			});
		}
		$("#overlay").show();
		$("#gatar").children(":first").children().css({ top: scr + 200 }).css("visibility","visible");
		$(".cl").click(function(){
			$("#overlay").hide();
			$(this).parent().parent().parent().fadeOut( 300, function(){$(this).remove();});
			return false;
		});

	},
	
	deletebid: function() {
		$(".deletebid").click( function() {
			bid = $(this).attr("id");
			$.ajax({
				url: '/ajax.php',
				type: 'post',
				data: 'acttype=deletebid&bid='+bid,
				dataType: 'xml',
				success: function(xml){
					parsercode(xml);
					start_functions();  
				},
				timeout: 6000
			});
			return false;
		});
	}, 
	
	biddeleted: function() {
		$("#"+bid).parent().parent().after(html[0]).remove();
	}

};

function start_functions() {
	if ( typeof(funcname) != 'undefined' ) {
		for( i=0; i <funcname.length; i++) {
			functions[funcname[i]](params[i]);	
		}
		delete funcname;
	}
}

// подгружает вызванный контент
jQuery.fn.loadform = function(typeform){
	var par = $(this);
	// height fix
	height = $(par).height();
	$(par).css('height', height);
	$.ajax({
		url: '/ajax.php?view=makeform',
		type: 'post',
		data: { 'acttype' : typeform },
		beforeSend: function(){
			$(par).html('<div class="loader"></div>');
		},
		dataType: 'xml',
		success: function(xml){
			parsercode(xml);
			if ( typeof (html[0]) != 'undefined') {			
				$(par).html('<div style="display: none;">'+html[0]+'</div>').children().fadeIn('fast');	
			}
			start_functions();
		},
		timeout: 6000,
		complete: function(){
			// end height fix
			$(par).css('height', 'auto');
		},
		error:function(){
			// end height fix
			prederr(text[2]);
			$(par).css('height', 'auto').html('');
		}
	});
};

// сохраняет данные в формах
jQuery.fn.saveform = function(acttype){
	$(this).live( 'submit', function(){
		data = $(this).serialize();
		data = data + '&acttype='+acttype;
		form = $(this);
		$.ajax({
			url: '/ajax.php',
			type: 'post',
			data: data,
			dataType: 'xml',
			success: function(xml){
				parsercode(xml);
				start_functions();
			},
			timeout: 6000
		});
		return false;
	});
};

// загружает попап
function loadbox( type, param ){
	data = 'parametr1='+param+'&acttype=box';
	$.ajax({
		url: '/ajax.php',
		type: 'post',
		data: data,
		dataType: 'xml',
		success: function(xml){
			parsercode(xml);
			start_functions();
		},
		timeout: 6000
	});
};


/* SecAjaxParser */
function parsercode(xml){
	// warnings errors messages
	var pred = new Array();
	$(xml).find('pred').each(function(){
		pred[pred.length] = $(this).text();				
	});
	if ( pred.length > 0) {
		prederr(pred);			
	}
	
	html = new Array();
	
	// html
	$(xml).find('html').each(function(){
		html[html.length] = $(this).text();
	});
	
	// js
	funcname = new Array();
	params = new Array();
	$(xml).find('script').each(function(){
		funcname[funcname.length] = $(this).find('funcname').text();
		params[funcname.length - 1] = new Array();
		$(this).find('parameter').each(function(){
			params[funcname.length - 1][$(this).find('name').text()] = $(this).find('value').text();
		});
	});
}

function ajaxFileUpload(acttype, mytid) {
	
	//starting setting some animation when the ajax starts and completes

	$.ajaxFileUpload({
		url:'/ajax.php', 
		secureuri:false,
		fileElementId:'imagetoupload',
		acttype: acttype,
		beforeSend: function(){
			$("#imgloader").show();	
		},
		mytid: mytid,
		dataType: 'xml',
		success: function (xml) {
			parsercode(xml);
			start_functions();
		},
		complete: function() {
			$("#imgloader").hide();	
		},
		error: function (data, status, e)
		{
			alert(e);
		}
	})
	
	return false;
}  

function getRandom(){
	var rand = Math.random()+' ';
	return rand.substr(2,3);
}