function ValidateForm(){

}

// Грузим fancybox
LoadCss('/js/fancybox/jquery.fancybox-1.3.1.css');
LoadScript('/js/fancybox/jquery.mousewheel-3.0.2.pack.js');
LoadScript('/js/fancybox/jquery.fancybox-1.3.1.pack.js');

(function($){
  $(function(){
  
  /*var warningText = "Внимание! Сайт работает в аварийном режиме. Вы видите спасенную копию от 11.02.2010. Работы по восстановлению и переходу сайта в рабочий режим будут продолжаться до 2 апреля. Все будет хорошо!";
  
  if(!(window.location.href.indexOf('udivland.ru')))
    $('<div id="attention">'+warningText+' <a href="#">Закрыть</a></div>')
      .css({
        position: 'absolute',
        top: '0',
        left: '0',
        width: '70%',
        textAlign: 'center',
        padding: '10px 15%',
        backgroundColor: '#000',
        opacity: '0.5',
        color: '#fff',
        zIndex: '1000'
      }).appendTo($('body')).find('a').css({
        color: '#fff',
        position: 'absolute',
        top: '10px',
        right: '15px'
      })
      .click(function() {
        $(this).parents('div#attention').hide();
        return false;
      });*/
  
  // Для всех форм, мы разрешаем их отправку только тогда, когда все ОБЯЗАТЕЛЬНЫЕ
  // поля заполнены
  $("form").live("submit.formValidate", function(event){
    var Sender = this;
    var Items = $(".required", $(this));
    var submitedForm = this;
    
    var Radios = {};
    var Fields = new Array();
  
    Items.each(function(){
    
      if(!$(this).is(":visible"))
        return;
              
      if(this.type == "text"
         && $(this).hasClass("not-valid-email") ){
      
        alert("Поле \"" + $(this).attr("title") + "\" должно иметь верное значение!");
        this.focus();   
        return false;  
      }
      
      if( $(this).hasClass("email") 
          && $(this).val()
          //&& ! /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i.test( $(this).val() ) ){
          && ! /^([a-z0-9\+_\-]+)(\.[a-z0-9\+_\-]+)*@([a-z0-9\-]+\.)+[a-z]{2,6}$/i.test( $(this).val() ) ){
        alert("Неправильный E-mail в поле «"+($(this).attr("title") ? $(this).attr("title") : $(this).attr("name") )+"»");
        this.focus();
        return;
      }
  
      // radio кнопки
      if( this.type == "radio" ) {
  
        if( !Radios[$(this).attr("name")] ){
          Radios[$(this).attr("name")] = {
            name: $(this).attr("name"),
            title: $(this).attr("title"),
            firstItem: this,
            values: new Array()
          };
        }
  
        Radios[$(this).attr("name")].values[$(this).attr("value")] = $(this).attr("text");
  
        if( $(this).attr("checked") )
          Radios[$(this).attr("name")].value = $(this).val();
      }
      else if( !$.trim($(this).val())
               && $.inArray(this.tagName.toLowerCase(), ["input", "textarea", "select"]) >= 0
               && $.inArray(this.type, ["checkbox", "hidden", "submit", "button"]) == -1 ) {
  
        var Regs = $(this).attr("title").split(/\s*\|\s*/);
  
        var Title = $(this).attr("name");
  
        if( Regs[0] )
          Title = Regs[0];
  
        Fields.push(Title);
  
        if( Fields.length == 1 )
          this.focus();
      }
    });
  
    $.each(Radios, function(){
  
      if( !$(this).val() ) {
  
        var Title = $(this).attr("name");
  
        var Regs = $(this).attr("title").split(/\s*\|\s*/);
  
        if( Regs[0] )
          Title = Regs[0];
  
        Fields.push(Title);
  
        //if( Fields.length == 1 )
          //this.focus(Radios[i].firstItem);
      }
    });
    
    //alert(Fields);
  
    if( Fields.length ) {
  
      alert("Пожалуйста, заполните пол" + (Fields.length == 1 ? "е":"я:") + " «" + Fields.join("», «") + "».");
  
      return false;
    }
    
    /*if(!$(this).hasClass("not-disabled")){
      $(this).find(":submit").each(function(){
        $("<input />").attr({
          type: "hidden",
          name: $(this).attr("name"),
          value: $(this).attr("value")
        }).appendTo(Sender);
      }).attr("disabled", "disabled").addClass("disabled");
    }*/
  
    return true;
  });
  
  // открытие фотографии в hs
  $("a.openInHs, a.openInPopup").fancybox({
    'margin' : 50,
    'titlePosition'    : 'inside',
    'hideOnContentClick' : true,
    'overlayShow': false,
    'showCloseButton'    : false,
    'titleFormat'        : function (title, currentArray, currentIndex, currentOpts) {
      return '<div id="tip7-title"><span><a href="javascript:;" onclick="$.fancybox.close();" title="Закрыть"><img src="/js/fancybox/closelabel.gif" alt="Закрыть" /></a></span>' + (title && title.length ? '<strong>' + title + '</strong>' : '' ) + (currentArray.length > 1 ? 'Изображение ' + (currentIndex + 1) + ' из ' + currentArray.length : '') + '</div>';
    }
  });
  
  // Для списка рурик интернет магазина
  // Скрsваем сильно глубокие деревья при просмотре всех ру,рик каталога
  $("ul.rubricList.jsOpened").find("ul.subList:not(.active)").hide().end()
  // И отображаем тока текущую рубрику дерева каталога
    .find("li:has(ul.subList) > a").click(function(e){
      $(this).next().toggle();
      e.preventDefault();
    });
});
})(jQuery);

/**
 * jQuery.timers - Timer abstractions for jQuery
 * Written by Blair Mitchelmore (blair DOT mitchelmore AT gmail DOT com)
 * Licensed under the WTFPL (http://sam.zoy.org/wtfpl/).
 * Date: 2009/10/16
 *
 * @author Blair Mitchelmore
 * @version 1.2
 *
 **/
jQuery.fn.extend({
	everyTime: function(interval, label, fn, times) {
		return this.each(function() {
			jQuery.timer.add(this, interval, label, fn, times);
		});
	},
	oneTime: function(interval, label, fn) {
		return this.each(function() {
			jQuery.timer.add(this, interval, label, fn, 1);
		});
	},
	stopTime: function(label, fn) {
		return this.each(function() {
			jQuery.timer.remove(this, label, fn);
		});
	}
});

jQuery.extend({
	timer: {
		global: [],
		guid: 1,
		dataKey: "jQuery.timer",
		regex: /^([0-9]+(?:\.[0-9]*)?)\s*(.*s)?$/,
		powers: {
			// Yeah this is major overkill...
			'ms': 1,
			'cs': 10,
			'ds': 100,
			's': 1000,
			'das': 10000,
			'hs': 100000,
			'ks': 1000000
		},
		timeParse: function(value) {
			if (value == undefined || value == null)
				return null;
			var result = this.regex.exec(jQuery.trim(value.toString()));
			if (result[2]) {
				var num = parseFloat(result[1]);
				var mult = this.powers[result[2]] || 1;
				return num * mult;
			} else {
				return value;
			}
		},
		add: function(element, interval, label, fn, times) {
			var counter = 0;
			
			if (jQuery.isFunction(label)) {
				if (!times) 
					times = fn;
				fn = label;
				label = interval;
			}
			
			interval = jQuery.timer.timeParse(interval);

			if (typeof interval != 'number' || isNaN(interval) || interval < 0)
				return;

			if (typeof times != 'number' || isNaN(times) || times < 0) 
				times = 0;
			
			times = times || 0;
			
			var timers = jQuery.data(element, this.dataKey) || jQuery.data(element, this.dataKey, {});
			
			if (!timers[label])
				timers[label] = {};
			
			fn.timerID = fn.timerID || this.guid++;
			
			var handler = function() {
				if ((++counter > times && times !== 0) || fn.call(element, counter) === false)
					jQuery.timer.remove(element, label, fn);
			};
			
			handler.timerID = fn.timerID;
			
			if (!timers[label][fn.timerID])
				timers[label][fn.timerID] = window.setInterval(handler,interval);
			
			this.global.push( element );
			
		},
		remove: function(element, label, fn) {
			var timers = jQuery.data(element, this.dataKey), ret;
			
			if ( timers ) {
				
				if (!label) {
					for ( label in timers )
						this.remove(element, label, fn);
				} else if ( timers[label] ) {
					if ( fn ) {
						if ( fn.timerID ) {
							window.clearInterval(timers[label][fn.timerID]);
							delete timers[label][fn.timerID];
						}
					} else {
						for ( var fn in timers[label] ) {
							window.clearInterval(timers[label][fn]);
							delete timers[label][fn];
						}
					}
					
					for ( ret in timers[label] ) break;
					if ( !ret ) {
						ret = null;
						delete timers[label];
					}
				}
				
				for ( ret in timers ) break;
				if ( !ret ) 
					jQuery.removeData(element, this.dataKey);
			}
		}
	}
});

jQuery(window).bind("unload", function() {
	jQuery.each(jQuery.timer.global, function(index, item) {
		jQuery.timer.remove(item);
	});
});

/**
 * Get the value of a cookie with the given name.
 *
 * @example $.cookie('the_cookie');
 * @desc Get the value of a cookie.
 *
 * @param String name The name of the cookie.
 * @return The value of the cookie.
 * @type String
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */
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;
    }
};
