Validation=function(options){this.options=options;this.form=$(options.form);this.errors={};var me=this;this.form.submit(function(){return me.validate()});for(field in this.options.fields){var validator=(function(field2){return function(){if(this.pressed)me.validate_field(field2,true)}})(field);this.form.find(field).blur(validator);this.form.find(field).keypress(function(ev){if(!this.pressed && ev.keyCode!=9)$(this).parent().addClass("pressed");if(ev.keyCode!=9)this.pressed=true})}};Validation.prototype={validate:function(){var me=this;for(field in this.options.fields){me.validate_field(field)};if(this.all_errors().length>0){this.show_errors();return false}else{return true}},validate_field:function(field,show_errors){var me=this;this.field=field;var value=this.form.find(field).removeClass("error").val();this.form.find(field).parent().removeClass("error-p");this.label_tag(field).find("small").remove();this.errors[field]=[];$(this.options.fields[field]).each(function(){return this(value,me)});if(show_errors)this.show_errors_for_field(field)},error:function(message){if(!this.errors[this.field])this.errors[this.field]=[];this.errors[this.field].push(message)},all_errors:function(){var me=this;var all_errors=[];for(field in this.errors){$(this.errors[field]).each(function(){all_errors.push(me.label_of(field)+" "+this)})};return all_errors},label_tag:function(field){return this.form.find("label[for="+field.replace(/^\#/,'')+"]")},label_of:function(field){return this.label_tag(field).html()},show_errors:function(){var me=this;var all_errors_container=me.form.find(".error-messages").show();if(all_errors_container.size()){var error_tag="p";if(all_errors_container.find("ul").size()>0){error_tag="li";all_errors_container=all_errors_container.find("ul")};all_errors_container.html(" ");$(this.all_errors()).each(function(){var p=$("<"+error_tag+">"+this+"</"+error_tag+">");all_errors_container.append(p)})}for(field in this.errors){this.show_errors_for_field(field)}},show_errors_for_field:function(field){if(this.errors[field].length==0)return false;var me=this;this.form.find(field).addClass("error").parent().addClass("error-p");var label=this.label_tag(field);text=$(this.errors[field]).map(function(){return"<small>"+this+""});label.append(text.get().join(",</small> ")+"</small>")}};Validation.presense=function(message){if(!message)message="необходимо заполнить";return function(value,object){if(value){return true}else{object.error(message);return false}}};Validation.length_in=function(f,t,message1,message2){if(!message1)message1="слишком короткое";if(!message2)message2="слишком длинное";return function(value,object){if(value.length<f){object.error(message1);return false};if(value.length>t){object.error(message2);return false}};return true};Validation.match=function(regexp,message){if(!message)message="имеет неверный формат";return function(value,object){if(value.match(regexp)){return true}else if(value){object.error(message);return false}else{ return true; }}};

function showBigImage(image, width, height, title)
{
	popupWin = window.open('/scripts/image.php?image=/'+image+'&w='+width+'&h='+height+'&title='+title,'','width='+width+', height='+height+', left=100, top=10, directories=no, location=no, menubar=no, resizable=yes, scrollbars=no, status=no, toolbar=no');
}


$(function() {
  $("a.fancybox").fancybox({hideOnContentClick: true});
  $("#add_cart_form").submit(function() {
    var form = $(this);
    $.post(form.attr("action"), form.serialize(), function(response) {
      // location.href = '/cart';
      // return true;
      
      $("#cart .empty").fadeOut('fast', function() {        
        $("#cart").html(response);
        $("#cart .empty").hide().fadeIn();
      });
    })
    return false;
  })

	CitySelect();	
})

	
function CitySelect() { 
	$("#citySelectForm").change( function() { 
		var cid = $(this).attr("value");
		var pid = $("#city_page_id").val();
		var catid = $("#city_cat_id").val();
		changeCity(cid, pid, catid);
	});
}

// >>> ajax изменение города, изменения заносятся в сессию
function changeCity(rid, pid, catid) {
  var m;
	$.ajax({
		type: "POST",
		cache: false,
		url: "/modulesAjax/city.php",
		data: "rid=" + rid + "&pid=" + pid + "&catid=" + catid,
		success: function(html) { 
		  if (m = html.match(/Redirect: (.+)/)){
		    location.href = m[1];
		  }else{
		    location.href = location.href;
        // setProductPriceOnCity(rid);
			}
		}
	});
}
// <<< ajax изменение города 

// >>> ajax изменение цен, используются специальные id
function setProductPriceOnCity(cid) {
	var sId = ""; var iid = "";
	var sget = "cid=" + cid; 
	var i = 0;
	$(".tov_cost").each( function() {  
		sId = $(this).attr('id');
		iid = sId.substr(5, sId.length);
		i++;
		sget = sget + "&" + "p" + i + "=" + iid;
	});
	
	$.ajax({
		type: "post",
		cache: false,
		url: "/modulesAjax/getPrice.php",
		data: sget,
		dataType: "json",
		success: function(res) { 
			var valPrice = "";
			for ( k in res ) {
				valPrice = ( res[k] != 'nulle' ? res[k] : "не указана" ) ;
				$("#"+k).html(valPrice);
			}
		}
	});
}
// <<< ajax изменение цен, используются специальные id
	


function input_only_int(input){
  input.keypress(function(e) {
    var chr = String.fromCharCode(e.which)
    if(e.which > 10 && (chr < "0" || chr > "9") && !(e.metaKey || e.altKey || e.shiftKey || e.ctrlKey)){
      return false;
    }
  })
}

function update_count(product_id, count){
  var data = {};
  $.post("/modulesAjax/cart.php", {action: 'update', product_id: product_id, count: count },function(response) {
    eval("data = " + response);
    $("#cart_one_" + product_id).html(data.cost);
    $("#cart_all_" + product_id).html(data.total);
    $("#total_all").html(data.total_all);
    
    // обновляем страницу если корзина пуста
    if (data.total_all.match(/^0 /)) location.href = location.href;
  })
}

function init_cart(){
  var count_confirm = $("#count-confirm");
  var product_id;
  var count;
  var original_count = 1;
  
  count_confirm.find("a.no").click(function() {
    count_confirm.hide();
    count_confirm.parent().find("input").val(count_confirm.original_count);
    return false;
  })
  count_confirm.find("a.yes").click(function() {
    count_confirm.hide();
    var title = count_confirm.parent().parent().parent();
    title.next().remove();
    title.remove();
    update_count(count_confirm.product_id, count_confirm.count);
    return false;
  })
  $("form.cart-form a.remove").click(function() {
    var remove_product_id = $(this).parent().find("input").attr("name").match(/\d+/)
    if (remove_product_id){
      
      var title = $(this).parent().parent().parent();
      title.next().remove();
      title.remove();
      
      remove_product_id = remove_product_id[0];
      update_count(remove_product_id, 0);
    }
    return false;
  })
  
  
  $("form.cart-form input").focus(function() {
    original_count = $(this).val();
  })
  $("form.cart-form input").change(function() {
    var me = $(this);
    product_id = me.attr("name").match(/\d+/);
    count = me.val();
    
    if (count == 0){
      me.parent().append(count_confirm);
      count_confirm.show();
      count_confirm.original_count = original_count;
      count_confirm.product_id = product_id;
      count_confirm.count = count;
    }else{
      update_count(product_id[0], count);
    }
  });
  input_only_int($("form.cart-form input"));
  
  $("#cart .clear-button a").click(function() {
    $.post("/modulesAjax/cart.php", {action: 'clear'}, function() {
      location.href = '/cart';
    })
    return false;
  })
}


function ru_name(i, name1, name2, name5){
  d = i % 100
  if( (d - d%10)/10 != 1)
    if (d%10 == 1) tip = "1"
    else if (d % 10 >= 2 && d % 10 <= 4) tip = "2"
    else tip = "5"
  else tip = "5";
  
  if (tip == 1) return i + " " + name1;
  if (tip == 2) return i + " " + name2;
  if (tip == 5) return i + " " + name5;
}

function city_notice_canvas_init(){
  var canvas = $('#canvas_note');
  var order_city = $("#order_city");
  var cart_order = $(".cart-order");
  var o1 = order_city.offset();
  var o2 = cart_order.offset();
  var y = o1.top - o2.top - cart_order.height();
  var x = o2.left - o1.left - order_city.width();
  canvas.attr("width",x);
  canvas.attr("height",y);
  canvas.css("left", order_city.position().left + order_city.width() + 30);
  canvas.css("top", -y + order_city.height() / 2);
  $(".fields2").css("position", "relative");
  if (canvas[0].getContext){
    var ctx = canvas[0].getContext('2d');
    ctx.strokeStyle = '#e1e1e1';
    ctx.beginPath();
    ctx.moveTo(0,y);
    ctx.lineTo(x,0);
    ctx.closePath();
    ctx.stroke();
  }
}

function show_city_notice(diff, city){
  var div = $("#city_notice");
  if (diff < 0){
    div.find(".value-add").hide();
    div.find(".value-red").show();
  }else{
    div.find(".value-add").show();
    div.find(".value-red").hide();
  }
  div.find(".value").html(ru_name(Math.abs(diff), "рубль", "рубля", "рублей"));
  div.find(".yes").html("Оставить " + city);
  
  div.show();
  div.parent().parent().find(".valid-presence").addClass("valid-presence-static");
  $('#canvas_note').show();
}

function init_order(){
  var city_notice = $("#city_notice");
  city_notice_canvas_init();
  city_notice.prev = $("#order_city").val();
  $("#order_city").change(function() {
    var select = this;
		var cid = $(this).attr("value");
		var pid = $("#city_page_id").val();
		var catid = $("#city_cat_id").val();
    $.post('/modulesAjax/cart.php', {action: 'city', city_id: cid}, function(response) {
      var old_price = $("#total_all").html();
      var new_price = response;
      var new_price_int = parseInt(new_price.replace(/\D/,''));
      var old_price_int = parseInt(old_price.replace(/\D/,''));
      if (new_price_int != old_price_int){
        show_city_notice(new_price_int - old_price_int, select.options[select.selectedIndex].innerHTML);
        
        $("#total_all").html(new_price);
      }
    })
    $("#citySelectForm").val($(this).val());
  })
  
  city_notice.find('.yes').click(function() {
    city_notice.hide();city_notice.parent().parent().find(".valid-presence").removeClass("valid-presence-static");$('#canvas_note').hide();
    city_notice.prev = $("#order_city").val();
    return false;
  })
  
  city_notice.find('.no').click(function() {
    $("#order_city").val(city_notice.prev);
    $("#citySelectForm").val(city_notice.prev);
    city_notice.hide();city_notice.parent().parent().find(".valid-presence").removeClass("valid-presence-static");$('#canvas_note').hide();
    $.post('/modulesAjax/cart.php', {action: 'city', city_id: city_notice.prev}, function(response) {
      $("#total_all").html(response);
    })
    return false;
  })

  // validation
  var fields = {};
  fields['#order_name'] = [Validation.presense("&nbsp;")]
  fields['#order_address'] = [Validation.presense("&nbsp;")]
  fields['#order_phone'] = [Validation.presense("&nbsp;"), Validation.match(/\d/)]
  fields['#order_email'] = [Validation.match(/^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i)]
  new Validation({ form: "#order_form", fields: fields });
}

function init_ie6(){
  $("a.maxnote").hover(function() {
    $(".maxnote-text").show();
  },function() {
    $(".maxnote-text").hide();
  })
}
