/**
 * jQuery.fn.sortElements
 * --------------
 * @author James Padolsey (http://james.padolsey.com)
 * @version 0.11
 * @updated 18-MAR-2010
 * --------------
 * @param Function comparator:
 *   Exactly the same behaviour as [1,2,3].sort(comparator)
 *   
 * @param Function getSortable
 *   A function that should return the element that is
 *   to be sorted. The comparator will run on the
 *   current collection, but you may want the actual
 *   resulting sort to occur on a parent or another
 *   associated element.
 *   
 *   E.g. $('td').sortElements(comparator, function(){
 *      return this.parentNode; 
 *   })
 *   
 *   The <td>'s parent (<tr>) will be sorted instead
 *   of the <td> itself.
 */
jQuery.fn.sortElements = (function(){
    
    var sort = [].sort;
    
    return function(comparator, getSortable) {
        
        getSortable = getSortable || function(){return this;};
        
        var placements = this.map(function(){
            
            var sortElement = getSortable.call(this),
                parentNode = sortElement.parentNode,
                
                // Since the element itself will change position, we have
                // to have some way of storing it's original position in
                // the DOM. The easiest way is to have a 'flag' node:
                nextSibling = parentNode.insertBefore(
                    document.createTextNode(''),
                    sortElement.nextSibling
                );
            
            return function() {
                
                if (parentNode === this) {
                    throw new Error(
                        "You can't sort elements if any one is a descendant of another."
                    );
                }
                
                // Insert before flag:
                parentNode.insertBefore(this, nextSibling);
                // Remove flag:
                parentNode.removeChild(nextSibling);
                
            };
            
        });
       
        return sort.call(this, comparator).each(function(i){
            placements[i].call(getSortable.call(this));
        });
        
    };
    
})();


function theRotator() {
	$('div#rotator ul li').css({opacity: 0.0});
	$('div#rotator ul li:first').css({opacity: 1.0});
	setInterval('rotate()', rotatorInterval);
}

function rotate() {	

	//Get the first image
	var current = ($('div#rotator ul li.show').length ?  $('div#rotator ul li.show') : $('div#rotator ul li:first'));

	//Get next image, when it reaches the end, rotate it back to the first image
	var next = ((current.next().length) ? ((current.next().hasClass('show')) ? $('div#rotator ul li:first') :current.next()) : $('div#rotator ul li:first'));	
	
	//Set the fade in effect for the next image, the show class has higher z-index
	next.css({opacity: 0.0})
		.addClass('show')
		.animate({opacity: 1.0}, rotatorInterval);

	//Hide the current image
	current.animate({opacity: 0.0}, rotatorInterval)
		.removeClass('show');
	
};



$(document).ready(function()
{
/*
	// баннеры на первой странице. изменить table на _table чтобы отключить
	$("table.items td.product").hover(
		function() 
		{
			id = $(this).attr('id');
			adv_html = $("#" + id + '_adv').html();
			
			if (!adv_html) return;
			
			if (!$("#banner_backup").html().length) { $("#banner_backup").html($(".banner").html()); }
			$(".banner").html(adv_html);
		},
		function() 
		{
			id = $(this).attr('id');
			if (adv_html = $("#" + id + '_adv').html().length) $(".banner").html($("#banner_backup").html());
		}
	);
*/	
	if ($('#rotator').length > 0) theRotator();
	
	$('table.sortable tr:odd').addClass('odd');

	if($.browser.msie && Number($.browser.version.substr(0,3)) == 6)
	{
		$('ul#nav li').each( function (i) {

			$(this).bind('mouseenter',  function (event) { $(this).toggleClass('over') });
			$(this).bind('mouseleave',  function (event) { $(this).toggleClass('over') });
			
		});

		$('ul#nav li ul').each( function (i) 
		{
			//left = $(this).parent().position().left - 25;
			$(this).css('margin-left' , '-11px');
			$(this).css('margin-top' , '1px');
			//$(this).css('border', '1px solid red');
		})
	}
	if($.browser.msie && Number($.browser.version.substr(0,3))  == 7)
	{
		$('ul#nav li ul').each( function (i) {
			left = $(this).parent().width() + 15;
			$(this).css('margin-left' , '-' + left + 'px');
			$(this).css('margin-top' , '-2px');
		})
	}
	
	$("li.cl_91 a:first").click(function() {
		if ($("li.cl_91 ul").is(":visible"))
		{
			$("li.cl_91 ul").hide();
			$("li.cl_91").toggleClass('on');
		}
		else
		{
			$("li.cl_91").toggleClass('on');
			$("li.cl_91 ul").show();
		}
	});
	$("li.cl_92 a:first").click(function() {
		if ($("li.cl_92 ul").is(":visible"))
		{
			$("li.cl_92 ul").hide();
			$("li.cl_92").toggleClass('on');
		}
		else
		{
			$("li.cl_92").toggleClass('on');
			$("li.cl_92 ul").show();
		}
	});

/*	$("select#shop_type").val(3);
	
	$(".shops table tr").hide();
	$(".shops table tr.type_" + $("select#shop_type").val()).show();
*/	$('table.sortable tr').removeClass('odd');
	$('table.sortable tr:odd:visible').addClass('odd');

	$("select#shop_type").change(function(){

		var type_id = $(this).val();
		var i = 0;

		$('.shops table tr').sortElements(
			function(a, b)
			{ 
				var aa = $(a).find('span.sort a[rel="' + type_id + '"]');
				var bb = $(b).find('span.sort a[rel="' + type_id + '"]');
				
				if (!aa.length) return 1;
				if (!bb.length) return -1;
				
//				$(a).removeClass('group_0');
//				$(a).addClass('group_' + aa.attr('ref'));
				
				val = aa.attr('ref') > bb.attr('ref') ? 1 : -1; 
				
				return val;
			}
		);
		
		$('.awards').removeClass('type_1 type_2 type_3 type_4 type_5')
					.addClass ('type_' + type_id);

		if ($(this).val() > 0)
		{
			$(".shops table tr").hide();
			$(".shops table tr.type_" + $(this).val()).show();
			$('table.sortable tr').removeClass('odd');
			$('table.sortable tr:odd:visible').addClass('odd');
		}
		else
		{
			$(".shops table tr").show();
			$('table.sortable tr').removeClass('odd');
			$('table.sortable tr:visible:odd').addClass('odd');
		}
	});


	
     	 
	$(function showpodmenu() {
		$("#citys_open").bind('mouseenter', function (event) {
			$("#citys").show();
		});
		$("#citys").bind('mouseleave', function (event) {
			$("#citys").hide();
		});
	})
	

	//console.log($("#calculator_formID"));

	// калькулятор
	var system = 2.300;
	var temp = 0.512;
	$("input[name=raid]").click(function()
	{
		var raid = parseInt($("input[@name=raid]:checked").val());
		$("#hdd").val();
		$("#results").html ('');
		$("#hdd").removeAttr('disabled');
		switch (raid)
		{
			case 0: 
				break;
			case 1:
				$("#hdd").attr('disabled', true);
				$("#hdd").val(2);
				break;
			case 5:
				break;
			case 6:
				break;
		}
	});
	
	function m(c, n)
	{
		msg  = new Array (
			'Превышает максимальное кол-во HDD доступное для установки в NAS Synology', 
			'Не задан объем жестких дисков',
			'Не задано кол-во жестких дисков', 
			'Число жестких дисков не может быть дробным',
			'Число и объем жестких дисков не может быть отрицательным',
			'Вы не указали количество жестких дисков или их объем.',
			'Для RAID0 необходимо минимум 2 диска', 
			'Для RAID1 необходимо не более 2 дисков', 
			'Для RAID5 необходимо минимум 3 диска', 
			'Для RAID5+Spare необходимо минимум 4 диска', 
			'Для RAID6 необходимо минимум 4 диска',
			'Объем диска не может быть больше 10TB и меньше 100GB'
		);
		$.validationEngine.buildPrompt("#" + c, msg[n], "error");
	}
	
	if($("#calculator_formID").length)
	{
		$("#calculator_formID").validationEngine({
			ajaxSubmit: true,
				ajaxSubmitFile: "/proc/null",
				ajaxSubmitMessage: "koko",
			inlineValidation: true,
			promptPosition: "topLeft",
			success : false,
			failure : function() {}
		});
	}

	//$("input[name=submit]").click(function() 
	$("form#calculator_formID").submit(function() 
	{ 
		if($.validationEngine.isError) { return false; }
		
		$("#results").html ('');

		var raid = Math.abs(parseInt($("input[@name=raid]:checked").val()));
		var hdd = Math.abs(parseInt($("#hdd").val()));
		var volume =Math.abs(parseInt($("#volume").val()));
		
		switch (raid)
		{
			case 0: 
				if (hdd < 2) { m('hdd', 6); }
				else { result = (volume - system - temp) * hdd; }
				break;
			case 1:
				if (hdd > 2) { m('hdd', 7); }
				else { result = (volume - system - temp) * hdd / 2; }
				break;
			case 5:
				if (hdd < 3) { m('hdd', 8); }
				else { result = (volume - system - temp) * (hdd - 1); }
				break;
			case 51:
				if (hdd < 4) { m('hdd', 9); }
				else { result = (volume - system - temp) * (hdd - 2); }
				break;
			case 6:
				if (hdd < 4) { m('hdd', 10); }
				else { result = (volume - system - temp) * (hdd - 2); }
				break;
		}

		result = Math.round((result * 100))/100;
		$("#results").html (result ? (result + 'Gb') : '');

		return false;
	});
});


function _chdt(o){e=o.form.elements;f=o.name.split('_')[0];
dd=e[f+'_dd'].options[e[f+'_dd'].selectedIndex].value;
mm=e[f+'_mm'].options[e[f+'_mm'].selectedIndex].value;
//alert(e[f+'_yy']?1:0);
yy=e[f+'_yy'].options?e[f+'_yy'].options[e[f+'_yy'].selectedIndex].value:1970;
if((mm==4||mm==6||mm==9||mm==11)&&dd>30){e[f+'_dd'].options.selectedIndex=29;return;}
if(mm==2&&dd>28)e[f+'_dd'].options.selectedIndex=(Math.floor(yy/4)==yy/4)?28:27;}

function _lt10(n){return n>9?n:'0'+n}

function _ctl_dtm(n,t,d,m,y,h,mi,s)
{
var mn=['','Январь','Февраль','Март','Апрель','Май','Июнь','Июль','Август','Сентябрь','Октябрь','Ноябрь','Декабрь'],w = '',z='<select name="'+n+'_dd"  class="day" onchange="_chdt(this)"'+w+'>'
for(var i=1;i<32;i++) z+='<option value="'+i+'"'+(i==d?' selected="selected"':'')+'>'+_lt10(i)+'</option>'
z+='</select><select name="'+n+'_mm" class="month"  onchange="_chdt(this)"'+w+'>'
for(i=1;i<mn.length;i++) z+='<option value="'+i+'"'+(i==m?' selected="selected"':'')+'>'+mn[i]+'</option>'
z+='</select><select name="'+n+'_yy" class="year" onchange="_chdt(this)"'+w+'>'
for(i=1970;i<2030;i++) z+='<option value="'+i+'"'+(i==y?' selected="selected"':'')+'>'+i+'</option>'
z+='</select>'
if(t){
z+='&nbsp;<select name="'+n+'_hh" onchange="_chdt(this)"'+w+'>'
for(i=0;i<23;i++) z+='<option value="'+i+'"'+(i==h?' selected="selected"':'')+'>'+_lt10(i)+'</option>'
z+='</select>:<select name="'+n+'_mi" onchange="_chdt(this)"'+w+'>'
for(i=0;i<60;i++) z+='<option value="'+i+'"'+(i==mi?' selected="selected"':'')+'>'+_lt10(i)+'</option>'
z+='</select>:<select name="'+n+'_mi" onchange="_chdt(this)"'+w+'>'
for(i=0;i<60;i++) z+='<option value="'+i+'"'+(i==s?' selected="selected"':'')+'>'+_lt10(i)+'</option>'
z+='</select>'
}
return z
}



/*Форма заявки*/

 $(document).ready(function() {
  $.viewInput = {
    '0' : $([]),
    'pole1' : $('#otherField'),
	'pole2' : $('#otherField2'),
  };

$('#otherFieldOption').change(function() {
    $.each($.viewInput, function() { this.hide("slow"); });
    $.viewInput[$(this).val()].slideDown("slow");
  });

});



$(document).ready(function() {
  $.viewInput2 = {
    '0' : $([]),
    'yes' : $('#otherField3'),
	'no' : $('#otherField4'),
  };
  

$('#otherFieldOption2').change(function() {
    $.each($.viewInput2, function() { this.hide("slow"); });
    $.viewInput2[$(this).val()].slideDown("slow");
  });

});


$(document).ready(function(){
	$(".sub_menu_ img").hover(function() {
		$(this).next("em").animate({opacity: "show", top: "-75"}, "slow");
	}, function() {
		$(this).next("em").animate({opacity: "hide", top: "-85"}, "fast");
	});


});
