var reqnumber = 0;
var cabinet_editsection = 0;

$(function() {
  a=$('.form .inptext, .form textarea')
  for(i=0; i<a.length; i++) {
   new changevalue($(a[i]))
  }
})

function changevalue(input) { //class
this.input = input
this.caption = $(input).val()
this.changed = false
var self = this
this.change = function() {
	if($(this.input).val()!='') {
		this.changed=true	
	} else {
		this.changed=false
	}
}
this.focus = function() {
	if(!this.changed) {
		$(this.input).val('')
	}	
}
this.blur = function() {
	if(!this.changed) {
		$(this.input).val(this.caption)
	}
}

$(input).bind('change', function() {self.change()})
$(input).bind('blur', function() {self.blur()})
$(input).bind('focus', function() {self.focus()})
}

$(document).ready(function(){
						   
	$(".photoalbum A[href$=.jpg], .photoalbum A[href$=.jpeg], .photoalbum A[href$=.gif], .photoalbum A[href$=.bmp]").fancybox({'overlayShow': false,'zoomSpeedIn': 500,'zoomSpeedOut': 500});
	
	$(".searchform").submit(function(){
		$("#cs").checked ? $(".searchform").attr("action","/price/"); : $(".searchform").attr("action","/search/");
	}
	
	$(".allphots A").click(function(){						
		/* var bw = $('body').width();
		var bh = $('body').height();
		bw = bw/2-200+'px';
		bh = bh/2-150+'px';
		$("#gallery").css('left',bw).css('top',bh); */
		$("#gallery").fadeIn(500);
		var galleries = $('.ad-gallery').adGallery();
		$('#switch-effect').change(
		  function() {
			galleries[0].settings.effect = $(this).val();
			return false;
		  }
		);
		$('#toggle-slideshow').click(
		  function() {
			galleries[0].slideshow.toggle();
			return false;
		  }
		);
	});
	$(".agclose").click(function(){
		$("#gallery").hide(500);
	});
	
	$(".tbl TR:even, .pricelist TR:even").css("background","#EEE");
	
	$('#user_registration_form [name="register_login"]').blur
	( /* проверка валидности и уникальности логина */
		function()
		{
			$('#login_ok').hide();
			$('#login_errors').show();
			var field = 'login';
			JsHttpRequest.query('?mod=cabinet&command=validate', {field: field, value: this.value},
			function(result, debugMessages)
			{
				if(result)
				{
					if(result.error)
					{
						$('#login_errors').html(jsErrors[result.error]);
					}
					else
					{
						$('#login_errors').hide();
						$('#login_ok').show();
					}
				}
				else
				{
					return false;
				}
			});
		}
	);
	
	$('#user_registration_form [name="register_password"], #user_registration_form [name="confirm_password"]').blur
	(
		function()
		{ /* проверка правильности пароля и подтверждения пароля */
			pass = $('#user_registration_form [name="register_password"]').val();
			conf = $('#user_registration_form [name="confirm_password"]').val();
			$('#password_ok').hide();
			$('#password_errors').show();
			if(pass=='')         $('#password_errors').html(jsErrors[4]);
			else if (conf=='')   $('#password_errors').html(jsErrors[5]);
			else if (pass!=conf) $('#password_errors').html(jsErrors[6]);
			else 				  
			{
				$('#password_errors').hide();
				$('#password_ok').show();
			}	
		}
	);
	
	$('#user_registration_form [name="register_email"]').blur
	(
		function()
		{ /* проверка правильности адреса e-mail */
			$('#email_ok').hide();
			$('#email_errors').show();
		
			var goodEmail = this.value.match(/\b(^([\.0-9a-zA-Z_-]+@[0-9a-zA-Z_\.-]+(\.[a-zA-Z]{2,4}){1,2})$)\b/gi);

			if(this.value=='')        $('#email_errors').html(jsErrors[7]);
			else if (!goodEmail) $('#email_errors').html(jsErrors[8]);
			else 	
			{
				$('#email_ok').show();
				$('#email_errors').hide();
			}
		}
	);
	
	$('#save_user_photo').click
	(
		function()
		{
			++reqnumber;
			url = '?mod=cabinet&command=submit_save_photo';
			JsHttpRequest.query(
			url, {data: this.form, token: reqnumber, save_photo_id: this.form.save_photo_id.value}, 
			function(result, errors) 
			{
				if (result) 
				{
					$('#photos_edit').hide();
					$('#user_photo_edit').hide();
					
					$('#single_photo_'+result.id+' .title').text(result.name);
					$('#single_photo_'+result.id+' .brief').text(result.desc);
					
					$('#photos_list').show();
					$('#user_photos_list').show();
					$('#new_photo_upload').show();
				}
			});
		}
	);
	
	$('#submit_load_photo').click
	(
		function()
		{
			++reqnumber;
			url = '?mod=cabinet&command=submit_load_photo';
			JsHttpRequest.query(
			url, {load_image: this.form, token: reqnumber}, 
			function(result, errors) 
			{
				if (result) 
				{	
					$('#single_photo_template .user_photo_edit').attr("href", "?action=edit&id="+result.id);
					$('#single_photo_template .user_photo_setmain').attr("href", "?action=delete&id="+result.id);
					$('#single_photo_template .user_photo_delete').attr("href", "?action=delete&id="+result.id);
					$('#user_photos_list').append($('#single_photo_template').clone(true));
					$('#user_photos_list #single_photo_template').attr("id", "single_photo_"+result.id);
					$('#single_photo_'+result.id+' .image').html('<img alt="" src="'+result.smallimage+'"/>');
					$('#single_photo_'+result.id+' .title').text(result.title);
					$('#single_photo_'+result.id+' .brief').text(result.desc);
				}
			});
		}
	);
	
	$('.user_photo_edit').click
	(
		function()
		{
			id = this.href.match(/id=(.*?)(?:&|$)/)[1];
			++reqnumber;
			url = '?mod=cabinet&action=edit&id='+id;
			JsHttpRequest.query(
				url, {token: reqnumber}, 
				function(result, errors) 
				{
					if (result) 
					{
						$('#photos_list').hide();
						$('#user_photos_list').hide();
						$('#new_photo_upload').hide();
						$('#user_photo_edit .image').html('<img alt="" src="/filestorage/cabinet/photos/small-'+result.id+'.'+result.image+'"/>');
						$('#save_photo_id').val(result.id);
						$('#edit_photo_name').val(result.name);
						$('#edit_photo_brieftext').val(result.brieftext);
						if(result.torate>0)
							$('#edit_photo_torate').attr("checked","checked");
						else		
							$('#edit_photo_torate').attr("checked","");
						$("input[@value='"+result.visibility+"']:radio").click();
						$('#photos_edit').show();
						$('#user_photo_edit').show();
					}
	
			});
			return false;
		}
	);
	
	$('.user_photo_setmain').click
	(
		function()
		{
			id = this.href.match(/id=(.*?)(?:&|$)/)[1];
			++reqnumber;
			url = '?mod=cabinet&action=setmain&id='+id;
			JsHttpRequest.query(
			url, {token: reqnumber}, 
			function(result, errors) 
			{
				if(result)
				{
					var pre = $('#avatar img').attr("src");
					$('#avatar img').attr("src", pre.replace(/\d+(?=\.[a-z]+$)/i, id))
				}
			});
			return false;		
		}
	);
	
	$('.user_photo_delete') .click
	(
		function()
		{
			id = this.href.match(/id=(.*?)(?:&|$)/)[1];
			++reqnumber;
			url = '?mod=cabinet&action=delete&id='+id;
			JsHttpRequest.query(
			url, {token: reqnumber}, 
			function(result, errors) 
			{
				if(result)
				{
					$('#single_photo_'+id).remove();
				}
			});
			return false;
		}
	);
	
	$('.profile_edit_section').click
	(
		function()
		{
			name = this.href.match(/edit=(.*?)(?:&|$)/)[1];
			if(cabinet_editsection)
			{
				$('#edit_section_'+cabinet_editsection).hide();
			}
			$('#view_section_'+name).hide();
			$('#view_section_'+cabinet_editsection).show();
			$('#edit_section_'+name).show();
			cabinet_editsection = name;
			return false;
		}
	);
	
	$('.profile_save_section').click
	(
		function()
		{
			++reqnumber;
			url = '?mod=cabinet&command=save_user_profile';
			success = false;
			JsHttpRequest.query(
				url, {
				data: this.form,
				token: reqnumber
				},
			function(result, debugMessages) {
			if(result.count)
			{
				for(i=0; i<result.count; i++)
				{
					$('#view_field_'+result.data[i].name).text(result.data[i].value);
					$('#currentuser_'+result.data[i].name).text(result.data[i].value);
				}
				$('#edit_section_'+cabinet_editsection).hide();
				$('#view_section_'+cabinet_editsection).show();
				cabinet_editsection = 0;
				success = false;
			}	
			else
			{
				success = true;
			}
			}
		);
		return success;
		}
	);
	
	$('.dclose').click(function(){
	  $('.dobavlen').fadeOut();
	});
	
	$('.xls_imported TR:first TD').addClass('xslth');
	$('.xls_imported TR:odd TD').addClass('xslodd');
	
	$('.xls_imported TR').not('.xls_imported TR:first').hover(function(){
		$(this).find('td').addClass('xslhover')
	  },function(){
		$(this).find('td').removeClass('xslhover')
	  });
	
	$('.pricelist TR').hover(function(){
		$(this).find('td').addClass('xslhover')
	  },function(){
		$(this).find('td').removeClass('xslhover')
	  });
	
});
	
var cabinet = // личный кабинет
{
	validateField: function(field, value, ismust)
	{
		$('#'+field+'_ok').hide();
		$('#'+field+'_errors').show();
		if(ismust && value=='')$('#'+field+'_errors').html(jsErrors[9]);
		else
		{
			$('#'+field+'_errors').hide();
			$('#'+field+'_ok').show();
		}
		
	}	
};

function addBookmark(url, title)  // добавить в избранное
{
 if (!url) url = location.href;
 if (!title) title = document.title;
 
 //Gecko
 if ((typeof window.sidebar == "object") && (typeof window.sidebar.addPanel == "function")) window.sidebar.addPanel (title, url, "");
 //IE4+
 else if (typeof window.external == "object") window.external.AddFavorite(url, title);
 //Opera7+
 else if (window.opera && document.createElement)
 {
   var a = document.createElement('A');
   if (!a) return false; //IF Opera 6
   a.setAttribute('rel','sidebar');
   a.setAttribute('href',url);
   a.setAttribute('title',title);
   a.click();
 }
 else return false;
}
	
var geography = // подгрузка городов и регионов
{
	loadCities: function(region)
	{
		success = false;
		++ reqnumber;
		JsHttpRequest.query(
			'?mod=geography&command=loadcities', {
				region: region, 
				token: reqnumber
				},
			function(result, debugMessages) {
			if(result)
			{
				$('#block_city').show();
				$('#city option').remove();
				for(i=0; i<result.ecount; i++)
				{
					city_id   = result.allnames[i].id;
					city_name = result.allnames[i].name;	
					$('#city').append("<option id='option_"+city_id+"' value='"+city_id+"'>"+city_name+"</option>");								
				}
				success = false;
			}	
			else
			{
				succcess = true;
			}
			
			}
		);
		return success;
	}
};

var shopcart = 
{
	additem: function(module, eid, sid, number)
	{
		success = false;
		++ reqnumber;
		JsHttpRequest.query(
		    '?mod=shopcart&command=addtocart',{
			token: reqnumber,
			from: module,
			id: eid,
			number: number,
			mod: sid
			},
		function(result, debugMessages){
			if(result)
			{
				$('#carttotal').text(result.total_num);
				$('#cartsomme').text(result.total_somme);
				success = false;
			}
			else
			{
				success = true;
			}} 
		);
		var le = document.body.clientWidth/2 - 370;
			var to = document.body.clientHeight/2 - 200;
			var width = le + 'px';
			var height = to + 'px';
			$('.dobavlen').css('left',width);
			$('.dobavlen').css('top',height);
			$('.dobavlen').fadeIn();
		return success;	
	}
};

function popup(file,width,height)
{
window.open(file,"","height="+height+",width="+width+",status=no,location=no,toolbar=no,directories=no,resizable=no,scrollbars=no,,menubar=no,top=10,left=10");
}
