jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};

var jq ={
	jQuery:jQuery.noConflict(),
	profile:{}
}

jq.profile.proceed={

	errors_map: {
		'email':'email_errors',
		'password':'password_errors'
	},

	init: function(){
		jq.jQuery(document).ready(function(){
			jq.jQuery("#btn_login").click(jq.profile.proceed.validate_login);
			jq.jQuery("#search_form_link").click(jq.profile.proceed.toggle_search_form);
			jq.jQuery("#add_note").click(function(){jq.profile.proceed.add_note();});
			jq.jQuery("#unote_unpin").click(function(){jq.profile.proceed.user_note_delete();});
			jq.jQuery("#agr_link").click(jq.profile.proceed.show_modal_agreement);
			jq.jQuery('.popupDatepicker').live("click",function(){
				jq.jQuery(this).datepick({showOn:'focus'}).focus();
			});
			jq.jQuery("#file_element").bind("change",jq.profile.proceed.upload_photo);
			jq.jQuery("#file_element_change").bind("change",jq.profile.proceed.upload_photo_forupdate);
			jq.jQuery(".init_note_form").live("click",jq.profile.proceed.show_note_form);
			jq.jQuery(".note_reset_btn").click(jq.profile.proceed.hide_note_button);
			jq.jQuery(".note_submit_btn").click(jq.profile.proceed.send_note);
			jq.jQuery(".delete_note").live("click",jq.profile.proceed.delete_note);
			jq.jQuery("#profile_select").change(jq.profile.proceed.switch_form_fields);
			jq.jQuery(".disable_search_cookie").click(jq.profile.proceed.disable_form_cookies);
			jq.jQuery("#search_link").click(jq.profile.proceed.enable_form_cookies);
		});
	},

	validate_login : function(){
		var data = {};
 		data.email = jq.jQuery("#login").val();
 		data.password = jq.jQuery("#password").val();
 		data.remember = jq.jQuery("#remember").val();

		var query_string="";

		for (n in data){
			vl = data[n];
			if (typeof(vl)=='object'){
				var joiner="&"+n+"[]=";
				vl=vl.join(joiner);
				n=n.toString()+"[]"
			}else{
				vl=vl.toString();
				vl=vl.replace(/[&=]/g, '')
			}
			query_string+=n+"="+vl+"&";
		}
		var newqs = query_string.replace(/[&=]$/g, '');

		jq.jQuery("#btn_login").val("Ждем");
		jq.jQuery("#btn_login").attr("disabled","disabled");
		jq.jQuery.ajax({
			type: "POST",
			url: "/content/validate_login/",
			data: newqs,
			dataType:'json',
			success: function(msg){
				jq.jQuery("#btn_login").removeAttr("disabled");
				jq.jQuery("#btn_login").val("Войти");
				jq.profile.proceed.validate(msg);
			}
		});
	},

	validate: function(msg){
		jq.jQuery("h6").remove();
		if (jq.profile.proceed.ok(msg)){
			window.location="/profile/";
		}else{
			for (i in msg.errors){
				if (jq.profile.proceed.errors_map[i]!=undefined){
					el=jq.jQuery("#"+jq.profile.proceed.errors_map[i]);
					el.html('<h6>'+msg.errors[i]+'<br /></h6>');
				}
			}
		}
	},

	ok : function (msg){
		for (i in msg.messages){
			if (msg.messages[i]=='[VALIDATED]'){return true;}
		}
		return false;
	},

	toggle_search_form : function(){
		if (jq.jQuery("#search_profiles_table").css("display")=='none'){
			jq.jQuery("#search_profiles_table").show();
			jq.jQuery("#search_form_link").text('Свернуть параметры поиска');
			jq.jQuery("#search_form_link").removeClass("sel_down");
			jq.jQuery("#search_form_link").addClass("sel_top");
			jq.jQuery.cookie("form", "shown",{domain:"4families.kz",path:"/"});
			//jq.jQuery.cookie("form", "shown",{domain:"aivanov.ru",path:"/"});
		}else{
			jq.jQuery("#search_profiles_table").hide();
			jq.jQuery("#search_form_link").text('Показать параметры поиска');
			jq.jQuery("#search_form_link").removeClass("sel_top");
			jq.jQuery("#search_form_link").addClass("sel_down");
			jq.jQuery.cookie("form", null,{domain:"4families.kz",path:"/"});
			//jq.jQuery.cookie("form", null,{domain:"aivanov.ru",path:"/"});
		}
	},

	disable_form_cookies : function(){
		jq.jQuery.cookie("form", null,{domain:"4families.kz",path:"/"});
		//jq.jQuery.cookie("form", null,{domain:"aivanov.ru",path:"/"});
	},

	enable_form_cookies : function(){
		jq.jQuery.cookie("form", "shown",{domain:"4families.kz",path:"/"});
		//jq.jQuery.cookie("form", "shown",{domain:"aivanov.ru",path:"/"});
	},

	add_note : function(){
		var user = jq.jQuery("#userid").val();
		jq.jQuery("#add_note").val('Подождите');
		jq.jQuery.ajax({
			type: "POST",
			url: "/content/add_note/",
			data: 'id='+user,
			dataType:'json',
			success: function(msg){
				jq.jQuery("#add_note").empty().val("Заметка добавлена");
			}
		});
	},

	user_note_delete : function(){
		var id = jq.jQuery("#pinid").val();
		jq.jQuery.ajax({
			type: "POST",
			url: "/content/delete_note/",
			data: 'id='+id,
			dataType:'json',
			success: function(msg){
				jq.jQuery("#pinid").parent().parent().css("background-color","#F00000").fadeOut();
			}
		});
	},

	show_modal_agreement : function(e){
		e.preventDefault();
		jq.jQuery.ajax({
			type: "POST",
			url: "/content/agreement/",
			data: 'id=agreement',
			success: function(data){
				jq.jQuery.nyroModalManual({
					bgColor: '#333333',
					content: data,
					width: 650,
					padding: 50
				});
			}
		});
	},

	upload_photo : function(){
		var obj_id = jq.jQuery(this).attr("id");
		//alert(obj_id);
		jq.profile.proceed.enable_photo_loader(obj_id);
		jq.jQuery.ajaxFileUpload(
			{
				url:'/content/upload_user_image/',
				secureuri:false,
				fileElementId:obj_id,
				dataType: 'json',
				success: function (data, status)
				{
					if (!data.error){
						jq.profile.proceed.set_file_options(obj_id,data);
					}else{
						jq.profile.proceed.set_file_error(obj_id,data);
					}

				},
				error: function (data, status, e)
				{
					console.log('Error data: '+data.error+'; status: '+status+';'+e);
					//alert('Error data: '+data.error+'; status: '+status+';'+e);
				}
			}
		)
	},

	enable_photo_loader : function(id){
		var con = jq.jQuery("#"+id).parent().parent().parent().children().find("#ajx_loader");
		var ajx = jq.jQuery("#ajax_loader_container").html();
		con.html(ajx);
	},

	set_file_options : function(id,data){
		var con = jq.jQuery("#"+id).parent().parent().parent().children().find("#ajx_loader");
		con.html(data.msg);
		jq.jQuery("#element").val(data.element);
	},

	set_file_options2 : function(id,data){
		var con = jq.jQuery("#"+id).parent().parent().parent().children().find("#ajx_loader");
		con.html(data.msg);
	},

	set_file_error : function(id,data){
		var con = jq.jQuery("#"+id).parent().parent().parent().children().find("#ajx_loader");
		con.html(data.error);
	},

	upload_photo_forupdate : function(){
		var obj_id = jq.jQuery(this).attr("id");
		jq.profile.proceed.enable_photo_loader(obj_id);
		jq.jQuery.ajaxFileUpload(
			{
				url:'/content/upload_user_image_update/',
				secureuri:false,
				fileElementId:obj_id,
				dataType: 'json',
				success: function (data, status)
				{
					if (!data.error){
						jq.profile.proceed.set_file_options2(obj_id,data);
					}else{
						jq.profile.proceed.set_file_error(obj_id,data);
					}

				},
				error: function (data, status, e)
				{
					console.log('Error data: '+data.error+'; status: '+status+';'+e);
				}
			}
		)
	},

	show_note_form : function(e){
		e.preventDefault();
		jq.jQuery(this).parent().parent("#note_navs").hide();
		jq.jQuery(this).parent().parent().parent().children("#note_list_container").show();
	},

	hide_note_button : function(){
		var form = jq.jQuery(this).parent().parent().parent().parent().parent().find("#note_list_container");
		var links = jq.jQuery(this).parent().parent().parent().parent().parent().find("#note_navs");
		form.hide();
		links.show();
	},

	send_note : function(){
		var id = jq.jQuery(this).parent().parent().parent().find("#user_id").val();
		var msg = jq.jQuery(this).parent().parent().parent().find("#text_note").val();
		if (msg == ''){
			alert('Вы не ввели текст заметки');
			return;
		}
		jq.jQuery.ajax({
			type: "POST",
			url: "/content/send_note_ajx/",
			data: 'id='+id+'&msg='+msg,
			success: function(data){
				var sel = data.replace(/"/g,'');
				jq.jQuery(".nlc_"+sel).hide();
				jq.jQuery(".nlcc_"+sel).show();
				jq.jQuery(".nlcc_"+sel+" #note_list_desc").html(msg);
				jq.jQuery(".nlcc_"+sel+" #note_list_link").empty();
				jq.jQuery(".nlcc_"+sel+" #note_list_link").append('<a href="#" class="delete_note">Удалить</a>');
				jq.jQuery(".nlcc_"+sel).addClass("active_note");
			}
		});
	},

	delete_note : function(e){
		e.preventDefault();
		var id = jq.jQuery(this).parent().parent().parent().children().find("#user_id");
		jq.jQuery.ajax({
			type: "POST",
			url: "/content/delete_note_ajx/",
			data: 'id='+id.val(),
			success: function(data){
				var sel = data.replace(/"/g,'');
				jq.jQuery(".nlcc_"+sel+" #note_list_desc").html('Видеть написанное будете только Вы.');
				jq.jQuery(".nlcc_"+sel+" #note_list_link").empty();
				jq.jQuery(".nlcc_"+sel+" #note_list_link").append('<a href="#" class="init_note_form">Изменить</a>');
				jq.jQuery(".nlcc_"+sel).removeClass("active_note");
			}
		});
	},

	switch_form_fields : function(){
		var type = jq.jQuery(this).val();
		var place = jq.jQuery("#dinamic_form_container");

		if (type == 1){
			place.empty();
			place.append(jq.jQuery("#container_users").html().replace(/\n|\t/g,''));
		}

		if (type == 2){
			place.empty();
			place.append(jq.jQuery("#container_employers").html().replace(/\n|\t/g,''));
		}

		if (type == 7){
			place.empty();
			place.append(jq.jQuery("#container_agency").html());
		}

		if (type == 9){
			place.empty();
			place.append(jq.jQuery("#container_kindergarten").html());
		}
	}
}
jq.profile.proceed.init();

function clean(sender){
	sender.value = '';
}
