function repf (obj, sSearch) {
	if( $(obj).val() == sSearch) {
		$(obj).val('');
	}
}

function repb (obj, sSearch) {
    if( $(obj).val() == '') {
        $(obj).val(sSearch);
    }
}


var wndids = new Array();
var wnddetails = new Array();
function parse_json(json) {
	
	updater = 0;
	updateid = 0;
	
	if(json == undefined || !json || json == '') return;
	json = eval( "(" + json + ")");
	if(json == undefined || !json || !json.length) return;
	
	for(var i in json)
	{
		if(json[i] == null || typeof(json[i].type)=='undefined') continue;
		
		switch(json[i].type)
		{
			case 'html':
				if(!json[i].id || json[i].id.length < 2) continue;
				var obj = $(json[i].id); if(!obj.length) continue;
				if (json[i].value) {
					//obj.html(json[i].value);
					var $new = json[i].value;
					obj.empty().append($new);
					//obj.show('fast');
				}
				else {
					//obj.hide('fast');
				}
				
				//if (json[i].name == 'actions') {
				//bindaction();
				//}
				
				break;
			case 'htmlappend':
				if(!json[i].id) continue;
				$(json[i].id).append(json[i].value);
				break;
			case 'html2':
				if(!json[i].id) continue;
				var obj = $(json[i].id); if(!obj.length) continue;

				if(json[i].nospan)
					var $new = $(json[i].value);
				else
					var $new = $('<span></span>').html(json[i].value);
				
				
				if (json[i].subtype == 'prepend') 
					obj.prepend($new);
				else 
				if (json[i].subtype == 'append') 
					obj.append($new);
				else 
				{
					obj.empty().append($new);
				}
				break;
			case 'inscr':
				apply_scripts(json[i].name);
				break;
				
			case 'code':
				window.eval(json[i].value);
				break;

			case 'alert':
			case 'msg':
				alert(json[i].value);
				continue;

			case 'go':
				window.location.href = json[i].value;
				continue;

			case 'remove':
				var obj = $('#'+json[i].name); if(!obj.length) continue;
				obj.remove();
				continue;
				
			case 'opwnd': 
				$('.opwnd').remove();
				if ( $('.opwnd').length == 0 ) {
					$('.opwndcover').show();
					
					dimensions = $.clientCoords();
					$('.opwndcover').css('height', $(document).height() + 'px');
					//alert( $(document).height() );
					
					obj = $("<div class='opwnd" + json[i].classname + "'></div>");
					obj.html('<div class=opwnda><!-- --></div><div class=opwndc onclick="return opwndclose();"><!-- --></div>' + '<div class=opwndcontent>' + json[i].value + '</div>');
					obj.appendTo($('body'));
                    
					if (json[i].stickobject == 'null') {
					    obj.center();
					    obj.css('left', parseInt(obj.css('left')) - 150 + 'px');
					    obj.css('top', parseInt(obj.css('top')) + 100 + 'px');
					}
					else {
					    x = $(json[i].stickobject).offset().left + $(json[i].stickobject).width();
					    y = $(json[i].stickobject).offset().top;
					    obj.css('left', (x + 10) + 'px');
					    obj.css('top', (y-13) +'px');
					}
					obj.width(json[i].width);
				}
				continue;

			case 'wnd':
					if (!wndids[json[i].wndid]) {
						obj = $("<div></div>");
						obj.html(json[i].value);
						
						
						var wndid = json[i].wndid;
						var details = json[i].details;
						
						var buttons = {};
			
						if (details && (details != 'undefined')) {
							buttons['Подробнее...'] = function() { ajaxreq(details, details); }
						}
						
						if (!json[i].nook) {
							if (json[i].okbutton)
								sOkButton = json[i].okbutton;
							else
								sOkButton = 'Сохранить';
							
							buttons[sOkButton] = function() { $(this).find('form').submit(); $(this).dialog('destroy').empty();wndids[wndid] = null; }
						}
						if (!json[i].noclose) {
							buttons['Закрыть'] = function() { $(this).dialog('destroy').empty();wndids[wndid] = null; }
						}
						
						dimensions = $.clientCoords();
						if (!json[i].width)
							json[i].width = dimensions.width - 200;
						if (!json[i].height)
							json[i].height = dimensions.height - 200;
						
						$(obj).dialog({
							title: json[i].caption,
							width:parseInt(json[i].width),
							height:parseInt(json[i].height),
							resizable: false,
							dialogClass: json[i].dclass,
							bgiframe: true,
							draggable: true,
							close: function(ev, ui) { wndids[wndid] = null; $(this).dialog('destroy').empty(); },
							position: "center",
							buttons: buttons
							/*buttons: {
								'Подробнее...': function() { ajaxreq(details, details); },
								'Закрыть': function() { $(this).dialog("close"); wndids[wndid] = null; }
							}*/
						 });
						 wndids[json[i].wndid] = obj;
					}
				break;
			case 'upl':
				make_upload(json[i]);
				continue;
			case '_msg':
				var wnd = $('#msg');
				if(wnd.length) wnd.dialog('destroy').empty(); else $('<div id=msg></div>').appendTo(document.body);
				
				$('#msg').html(json[i].value).
				dialog({
					bgiframe:false,
                    autoOpen:true,
					resizable: false,
                    title:json[i].title?json[i].title:'',
                    modal:true,
					buttons: { Ok: function() { $(this).dialog('close'); } }
					}).
				bind('dialogclose', function(event, ui) {	$(this).dialog('destroy').empty(); });
				continue;
			case 'wnd2':
				var wnd = $(json[i].id);
				if(wnd.length) wnd.dialog('destroy').remove();
				
				$(json[i].value).appendTo(document.body);
				
                var buttons = {};
                var details = json[i].details;
                
                if (details && (details != 'undefined')) {
                    buttons['Подробнее...'] = function() { ajaxreq(details, details); }
                }
                
                if (!json[i].nook) {
                    if (json[i].okbutton)
                        sOkButton = json[i].okbutton;
                    else
                        sOkButton = 'Сохранить';
                    
                    buttons[sOkButton] = function() { $(this).find('form').submit(); $(this).dialog('destroy').remove(); }
                }
                if (!json[i].noclose) {
					buttons['Закрыть'] = function() { $(this).dialog('destroy').remove(); }
				}
                        
				$(json[i].id).
				dialog({
					bgiframe:false,
                    autoOpen:true,
                    title:json[i].title,
                    modal:true,
                    buttons: buttons,
                    position: "center",
                    width:parseInt(json[i].width),
					height:parseInt(json[i].height),
					resizable: false,
					dialogClass: json[i].dclass
                }).
				bind('dialogclose', function(event, ui) { $(this).dialog('destroy').remove(); });
				$(json[i].id).dialog('option', 'position', $(json[i].id).dialog('option', 'position'));
				continue;
		}
	}
}

$.clientCoords = function() {
     var dimensions = {width: 0, height: 0};
     if (document.documentElement) {
         dimensions.width = document.documentElement.offsetWidth;
         dimensions.height = document.documentElement.offsetHeight;
     } else if (window.innerWidth && window.innerHeight) {
         dimensions.width = window.innerWidth;
         dimensions.height = window.innerHeight;
     }
     return dimensions;
}

function toggleDetails () {
    $('table.parameters').toggle();
    $('.details div').toggleClass('collapsed');
}

function toggleConfigurator () {
	$('#configurator_body').toggle();
	$('.forma .ugol a.oc').toggleClass('close');
}


/*function nextImage() {
	if ($(".biggest #bannerplace .one:last").is(":visible")) {
			$(".biggest #bannerplace .one:visible").fadeOut('fast',function(){
				$(".biggest #bannerplace .one:first").fadeIn('fast');
			});
	}
	else {
			$(".biggest #bannerplace .one:visible").fadeOut('fast',function(){
				$(this).next().fadeIn('fast');
			});
	}
}

function prevImage() {
	if ($(".biggest #bannerplace .one:first").is(":visible")) {
			$(".biggest #bannerplace .one:visible").fadeOut('fast',function(){
				$(".biggest #bannerplace .one:last").fadeIn('fast');
			});
	}
	else {
			$(".biggest #bannerplace .one:visible").fadeOut('fast',function(){
				$(this).prev().fadeIn('fast');
			});
	}
}*/

function toCart (nId, bt, tp, start, month)
{
    $.post('/cart/func/add/id/' + nId + '/bt/' + bt + '/tp/' + tp + '/start/' + start + '/month/' + month, {}, parse_json);
	return false;
}

function orderItem (nId)
{
    $.post('/catalog/item/order/id/' + nId, {}, parse_json);
	return false;
}

function ajreq (sUrl, data)
{
	$.post(sUrl, {data: data}, parse_json);
	return false;
}

function compareAdd (nId)
{
    if ($('#comp' + nId).is(':checked'))
        task = 'add';
    else
        task = 'remove';
    $.post('/compare/func/' + task + '/id/' + nId, {}, parse_json);
	return false;
}

function opwndclose () {
	$('.opwnd').remove();
	$('.opwndcover').hide();
	return false;
}

jQuery.fn.center = function () {
    this.css("position","absolute");
    this.css("top", ( $(window).height() - this.height() ) / 2+$(window).scrollTop() + "px");
    this.css("left", ( $(window).width() - this.width() ) / 2+$(window).scrollLeft() + "px");
    return this;
}

function equalizer (sCollection) {
    var nMaxHeight = 0;
    $(sCollection).each(function () {
        if ( $(this).height() > nMaxHeight )
            nMaxHeight = $(this).height();
    });

    $(sCollection).each(function () {
        $(this).height(nMaxHeight);
    });    
}

function checktab(tabid, liid)
{
	$('.korz .tabs.tab' + tabid + ' li.active').removeClass('active');
	$('.korz .tabs.tab' + tabid + ' li.la' + liid).addClass('active');
}

function checkmegatab(tabid)
{
	//$('.korz .tabs.tabs').hide();
	//$('.korz .tabs.tab' + tabid).show();
	//$('.vitrina .tab').removeClass('active');
	//$('.vitrina .tab_' + tabid).addClass('active');
}

function resetForm(id) {
	$(id).each(function(){
	        this.reset();
	});
}

function showaddform () {
	$('.addrform').show();
	$('.cabinet_addresses_one_radio input').removeAttr('checked');
	$('.deliveryAddress').html ('');
}

function checkaddress ()
{
	if ( $('input[name=defaultaddress]').filter(':checked').val() > 0 )
	{
		$('.deliveryAddress').html ( $('input[name=defaultaddress]').filter(':checked').parents('.cabinet_addresses_one').find('.cabinet_addresses_one_address').html() );
	}
	
	if ($('.deliveryAddress').html () == '')
	{
		sRegion = $('.addrform input[name=newaddress_region]').val();
		sCity = $('.addrform input[name=newaddress_address_city]').val();
		sStreet = $('.addrform input[name=newaddress_street]').val();
		sHome = $('.addrform input[name=newaddress_address_home]').val();
		sCorpus = $('.addrform input[name=newaddress_address_korpus]').val();
		sFlat = $('.addrform input[name=newaddress_address_flat]').val();
		sCode = $('.addrform select').val();
		sPhone = $('.addrform input[name=newaddress_address_phone]').val();
		sResult = '<div class=cabinet_addresses_one_local>' + sStreet + ' ' + sHome;
		if (sCorpus)
			sResult = sResult + '-' + sCorpus;
		
		sResult = sResult + '-' + sFlat + '</div><div class=cabinet_addresses_one_global>';
		
		if (sRegion)
			sResult = sRegion + ', ';
		
		sResult = sResult + sCity + '</div><div class=cabinet_addresses_one_phone>Телефон: ' + sCode + ' ' + sPhone;
		$('.deliveryAddress').html ( sResult );
		
	}
}

function CurrencyFormatted(nStr)
{
	nStr += '';
	x = nStr.split('.');
	x1 = x[0];
	x2 = x.length > 1 ? '.' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + ' ' + '$2');
	}
	return x1 + x2 + ' руб.';
}


function checkpaydelcost()
{
	sPostCity = $('select[name=post_city]').val();
	sPrice = $('input[name=hiddenPrice]').val();
	sItems = $('input[name=hiddenItems]').val();
	sPayType = $('input[name=paytype]').filter(':checked').val();
	sDeliveryType = $('input[name=deliverytype]').filter(':checked').val();
	sServiceTP = $('select[name=service_tp]').val();
	ajreq('/cart/func/calc/price/' + sPrice + '/pt/' + sPayType + '/stp/' + sServiceTP + '/dt/' + sDeliveryType + '/pc/' + sPostCity + '/hi/' + sItems);
	
}

function checkcartform () {
	if ( $('input[name=paytype]').filter(':checked').val() == 'credit')
	{
		aCheckFields = new Array(
			'input[name=credit_name]',
			'input[name=credit_family]',
			'input[name=credit_faname]',
			'input[name=credit_birthdate]',
			'input[name=credit_birthyear]',
			'input[name=credit_phone]',
			'input[name=credit_city]',
			'input[name=credit_address]',
			'input[name=credit_phonehome]',
			'input[name=credit_passport]',
			'input[name=credit_passportfromdate]',
			'input[name=credit_passportfromyear]',
			'input[name=credit_passporttodate]',
			'input[name=credit_passporttoyear]',
			'input[name=credit_privatenumber]',
			'input[name=credit_issue]',
			'input[name=credit_registryaddress]',
			'input[name=credit_registrydate]',
			'input[name=credit_registryyear]',
			'input[name=credit_workplace]',
			'input[name=credit_workaddress]',
			'input[name=credit_workstatus]',
			'input[name=credit_workphone]',
			'input[name=credit_nearfio]',
			'input[name=credit_nearaddress]',
			'input[name=credit_nearphone]'
			);
		bPass = true;
		for(var elm in aCheckFields)
		{
			if ( $( aCheckFields[ elm ] ).val() == '' )
			{
				$(aCheckFields[ elm ] ).addClass('error');
				bPass = false;
			}
		}
		if (!bPass)
		{
			checkmegatab(1);
			return false;

		}
	}
	
	if ( $('input[name=paytype]').filter(':checked').val() == 'rass')
	{
		aCheckFields = new Array(
			'input[name=rassr_name]',
			'input[name=rassr_family]',
			'input[name=rassr_faname]',
			'input[name=rassr_birthdate]',
			'input[name=rassr_birthyear]',
			'input[name=rassr_phone]',
			'input[name=rassr_city]',
			'input[name=rassr_address]',
			'input[name=rassr_phonehome]',
			'input[name=rassr_passport]',
			'input[name=rassr_passportfromdate]',
			'input[name=rassr_passportfromyear]',
			'input[name=rassr_passporttodate]',
			'input[name=rassr_passporttoyear]',
			'input[name=rassr_privatenumber]',
			'input[name=rassr_issue]',
			'input[name=rassr_registryaddress]',
			'input[name=rassr_registrydate]',
			'input[name=rassr_registryyear]',
			'input[name=rassr_workplace]',
			'input[name=rassr_workaddress]',
			'input[name=rassr_workstatus]',
			'input[name=rassr_workphone]',
			'input[name=rassr_nearfio]',
			'input[name=rassr_nearaddress]',
			'input[name=rassr_nearphone]'
			);
		bPass = true;
		for(var elm in aCheckFields)
		{
			if ( $( aCheckFields[ elm ] ).val() == '' )
			{
				$(aCheckFields[ elm ] ).addClass('error');
				bPass = false;
			}
		}
		if (!bPass)
		{
			checkmegatab(1);
			return false;

		}
	}
	
	if ( $('input[name=paytype]').filter(':checked').val() == 'service')
	{
		
		aCheckFields = new Array(
			'input[name=service_name]',
			'input[name=service_family]',
			'input[name=service_faname]',
			'input[name=service_birthdate]',
			'input[name=service_birthyear]',
			'input[name=service_phone]',
			'input[name=service_email]',
			'input[name=service_passport]',
			'input[name=service_passportfromdate]',
			'input[name=service_passportfromyear]',
			'input[name=service_passporttodate]',
			'input[name=service_passporttoyear]',
			'input[name=service_privatenumber]',
			'input[name=service_issue]',
			'input[name=service_registryaddress]',
			'input[name=service_registrydate]',
			'input[name=service_registryyear]'
			);
		bPass = true;
		
		if ( 
				!$('select[name=service_tp]').val() || 
				($('select[name=service_tp]').val() == '0') || 
				($('select[name=service_tp]').val() = 0)
			)
		{
			$('select[name=service_tp]').addClass('error');
			bPass = false;
		}
		
		for(var elm in aCheckFields)
		{
			if ( $( aCheckFields[ elm ] ).val() == '' )
			{
				$(aCheckFields[ elm ] ).addClass('error');
				bPass = false;
			}
		}
		if (!bPass)
		{
			checkmegatab(1);
			return false;

		}
	}
	
	if ( $('input[name=paytype]').filter(':checked').val() == 'beznal')
	{
		aCheckFields = new Array(
			'input[name=beznal_company]',
			'input[name=beznal_address]',
			'input[name=beznal_unp]',
			'input[name=beznal_bank]',
			'input[name=beznal_bankaddress]',
			'input[name=beznal_rs]',
			'input[name=beznal_osnovanie]',
			'input[name=beznal_director]',
			'input[name=beznal_phone]',
			'input[name=beznal_buyer]'
			);
		bPass = true;
		for(var elm in aCheckFields)
		{
			if ( $( aCheckFields[ elm ] ).val() == '' )
			{
				$(aCheckFields[ elm ] ).addClass('error');
				bPass = false;
			}
		}
		if (!bPass)
		{
			checkmegatab(1);
			return false;

		}
	}
	
	
	if ( !$('input[name=defaultaddress]').filter(':checked').size() )
	{
		
		bPass = true;
		
		aCheckFields = new Array(
			'input[name=newaddress_address_city]',
			'input[name=newaddress_street]',
			'input[name=newaddress_name]',
			'input[name=newaddress_address_home]',
			'input[name=newaddress_address_phone]'
			);
		bPass = true;
		for(var elm in aCheckFields)
		{
			if ( $( aCheckFields[ elm ] ).val() == '' )
			{
				$(aCheckFields[ elm ] ).addClass('error');
				bPass = false;
			}
		}


		if (!bPass)
		{
			checkmegatab(3);
			return false;

		}
	}
	
	if ( $('input[name=deliverytype]').filter(':checked').val() == 'post')
	{
		
	}
	
	return true;
}
	
$(function() {
    $(document).ajaxStart(function(){
		$("#fancybox-loading").show();
	}).ajaxStop(function(){ 
		$("#fancybox-loading").hide();
	});
	
	 $('a.fotoimg').livequery(function() {
        $(this).fancybox({ 'hideOnContentClick': true, 'overlayShow': false,  'zoomSpeedIn': 300, 'zoomSpeedOut': 300, 'zoomOpacity': true, 'overlayShow' : true, 'overlayOpacity' : 0.5 });
     });
     
	$('.catalogmenu li').bind('mouseenter', function() {
		$(this).children('ul').show();
		
		});
	$('.catalogmenu li').bind('mouseleave', function() {
		$('ul', this).hide();
		
		});
		
		
	$('#menu li').bind('mouseenter', function() {
		$(this).children().show();
		
		});
	$('#menu li').bind('mouseleave', function() {
		$('ul', this).hide();
		
		});
		
	$("a.videoimg").livequery(function(){
		$(this).fancybox({ 'imageScale': false, 'autoScale'	: false, 'hideOnContentClick': false, 'width': 380, 'height': 280, 'overlayShow': true, 'zoomOpacity': true, 'zoomSpeedIn': 300, 'zoomSpeedOut': 300, easingIn: 'easeOutBack', easingOut: 'easeInBack' });	
	});

	$('.catalog_gallery .one .img').bind('click', function () {
		sImg = $(this).attr('rel');
		$('.coverimg .coverimg_img').css('background-image', 'url(' + sImg + ')')
	});

	$('.item_gallery .item_one').bind('click', function () {
		sImg = '/mdlimg.php?imgname=' + $(this).attr('rel') + '&w=400&h=400';
		sBigImg = '/' + $(this).attr('rel');
		$('.item_gallery .item_right img').attr('src', sImg);
		$('.item_gallery .item_right a').attr('href', sBigImg);
		$('.item_gallery .item_one').removeClass('active');
		$(this).addClass('active');
	});

	
});

