var rootPath = "http://mmcentr.ru/" ;
//var rootPath = "http://localhost/mmcentr/" ;
//****************************************************
//-------- меню jQuery ------------------------------

jQuery.fn.initMenu = function() {  
    return this.each(function(){
        var theMenu = $(this).get(0);
        $('.acitem', this).hide();
        $('li.expand > .acitem', this).show();
        $('li.expand > .acitem', this).prev().addClass('active');
        $('li a', this).click(
            function(e) {
                e.stopImmediatePropagation();
                var theElement = $(this).next();
                var parent = this.parentNode.parentNode;
                if($(parent).hasClass('noaccordion')) {
                    if(theElement[0] === undefined) {
                        window.location.href = this.href;
                    }
                    $(theElement).slideToggle('normal', function() {
                        if ($(this).is(':visible')) {
                            $(this).prev().addClass('active');
                        }
                        else {
                            $(this).prev().removeClass('active');
                        }    
                    });
                    return false;
                }
                else {
                    if(theElement.hasClass('acitem') && theElement.is(':visible')) {
                        if($(parent).hasClass('collapsible')) {
                            $('.acitem:visible', parent).first().slideUp('normal', 
                            function() {
                                $(this).prev().removeClass('active');
                            }
                        );
                        return false;  
                    }
                    return false;
                }
                if(theElement.hasClass('acitem') && !theElement.is(':visible')) {         
                    $('.acitem:visible', parent).first().slideUp('normal', function() {
                        $(this).prev().removeClass('active');
                    });
                    theElement.slideDown('normal', function() {
                        $(this).prev().addClass('active');
                    });
                    return false;
                }
            }
        }
    );
});
};

$(document).ready(function() {$('.menu').initMenu();});

//****************************************************

	/*if(document.getElementsByClassName) {
	 
	    getElementsByClass = function(classList, node) {   
	        return (node || document).getElementsByClassName(classList)
	    }
	 
	} else {
	 
	    getElementsByClass = function(classList, node) {           
	        var node = node || document,
	        list = node.getElementsByTagName('*'),
	        length = list.length, 
	        classArray = classList.split(/\s+/),
	        classes = classArray.length,
	        result = [], i,j
	        for(i = 0; i < length; i++) {
	            for(j = 0; j < classes; j++)  {
	                if(list[i].className.search('\\b' + classArray[j] + '\\b') != -1) {
	                    result.push(list[i])
	                    break
	                }
	            }
	        }
	     
	        return result
	    }
	}*/
	
// Динамический select принтеров
	function select_model()	{
		var brand_id = $('#brand').val() ;
		if (brand_id == '0') {
            $('#model').html('');
            $('#model').attr('disabled', true);
            return(false);
        }
		$('#model').attr('disabled', true);
        $('#model').html('<option>загрузка...</option>');
		
		var url = rootPath + 'cgi/search/get_models.php';
		$.get(
            url,
            "brand=" + brand_id,
            function (result) {
                /*
                 * В случае неудачи мы получим результат с type равным error.
                 * Если все прошло успешно, то в type будет success,
                 * а также массив regions, содержащий данные по регионам
                 * в формате 'id'=>'1', 'title'=>'название региона'.
                 */
                if (result.type == 'error') {
                    /*
                     * ошибка в запросе
                     */
                    alert('error');
                    return(false);
                }
                else {
                    /*
                     * проходимся по пришедшему от бэк-энда массиву циклом
                     */
					 //alert(result.regions) ;
                    var options = '';
                    $(result.models).each(function() {
                        /*
                         * и добавляем в селект по региону
                         */
                        options += '<option value="' + $(this).attr('value') + '">' + $(this).attr('name') + '</option>';
                    });
                    $('#model').html(options);
                    $('#model').attr('disabled', false);
                }
            },
            "json"
        );
		
	}
	
	
	
	
	

// Динамический select городов

    function select_t () {
        /*
         * В переменную country_id положим значение селекта
         * (выбранная страна)
         */
        var region_id = $('#region').val();
        /*
         * Если значение селекта равно 0,
         * т.е. не выбрана страна, то мы
         * не будем ничего делать
         */ 
		 //document.write(region_id) ;
		 if (region_id == '0') {
            $('#town').html('');
            $('#town').attr('disabled', true);
            return(false);
        }
        /*
         * Очищаем второй селект с регионами
         * и блокируем его через атрибут disabled
         * туда мы будем класть результат запроса
         */
        $('#town').attr('disabled', true);
        $('#town').html('<option>загрузка...</option>');
        /*
         * url запроса регионов
         */
        var url = rootPath + 'cgi/prgreg/get_towns.php';
        
        /*
         * GET'овый AJAX запрос
         */
        $.get(
            url,
            "region=" + region_id,
            function (result) {
                /*
                 * В случае неудачи мы получим результат с type равным error.
                 * Если все прошло успешно, то в type будет success,
                 * а также массив regions, содержащий данные по регионам
                 * в формате 'id'=>'1', 'title'=>'название региона'.
                 */
                if (result.type == 'error') {
                    /*
                     * ошибка в запросе
                     */
                    alert('error');
                    return(false);
                }
                else {
                    /*
                     * проходимся по пришедшему от бэк-энда массиву циклом
                     */
					 //alert(result.regions) ;
                    var options = '';
                    $(result.regions).each(function() {
                        /*
                         * и добавляем в селект по региону
                         */
                        options += '<option value="' + $(this).attr('id') + '">' + $(this).attr('name') + '</option>';
                    });
                    $('#town').html(options);
                    $('#town').attr('disabled', false);
                }
            },
            "json"
        );
        
    };


function show_descipt ( del_way ) {
	$('.descr_class').hide() ;
	//alert ( del_way ) ;
	var url = rootPath + 'cgi/order/show_desc_delivery.php';
	$.get(
            url,
            "delivery=" + del_way,
            function (result) {
			
				$('#'+ result.id).html(result.text);
                $('#'+ result.id).attr('style', '');
			}, 
			"json"
		) ;
	
}

function show_descipt_pay ( pay_way ) {
	$('.descr_class').hide() ;
	//alert ( pay_way ) ;
	var url = rootPath + 'cgi/order/show_desc_pay.php';
	$.get(
            url,
            "pay=" + pay_way,
            function (result) {
			
				$('#'+ result.id).html(result.text);
                $('#'+ result.id).attr('style', '');
			}, 
			"json"
		) ;
	
}





$(document).ready(function() {	
	//alert (location.href) ;
	xajax_fill_modal() ;
	//select all the a tag with name equal to modal
	$('a[name=modal]').click(function(e) {
		//Cancel the link behavior
		e.preventDefault();
		
		//Get the A tag
		var id = $(this).attr('href');
	
		//Get the screen height and width
		var maskHeight = $(document).height();
		var maskWidth = $(window).width();
	
		//Set heigth and width to mask to fill up the whole screen
		$('#mask').css({'width':maskWidth,'height':maskHeight});
		
		//transition effect		
		$('#mask').fadeIn(1000);	
		$('#mask').fadeTo("slow",0.8);	
	
		//Get the window height and width
		var winH = $(window).height();
		var winW = $(window).width();
              
		//Set the popup window to center
		$(id).css('top',  winH/2-$(id).height()/2);
		$(id).css('left', winW/2-$(id).width()/2);
	
		//transition effect
		$(id).fadeIn(2000); 
	
	});
	
	//if close button is clicked
	$('.window .close').click(function (e) {
		//Cancel the link behavior
		e.preventDefault();
		$('#mask, .window').hide();
	});		
	
	//if mask is clicked
	$('#mask').click(function () {
		$(this).hide();
		$('.window').hide();
	});			
	
	$('#full_img').click(function () {
		$(this).hide();
		$('#mask').hide();
	});
	
});

//-------- подмена изображений при наступлении события

function changeImgOn ( img_id, path ) {
		var asd = document.getElementById ( img_id ) ;
		asd.setAttribute ( "src", path ) ;
		
}
	
function changeImgOff ( img_id, path ) {
		var asd = document.getElementById ( img_id ) ;
		asd.setAttribute ( "src", path ) ;
		
}

 function Calculate() {
     var ob = document.getElementsByName( "nums[]" ) ;    
     var tp = 0 ;
     
     for( i = 0 ; i < ob.length ; i++ ) {
         if( Number( ob.item(i).value ) )
             tp += ob.item(i).attributes.each.value * ob.item(i).value ;
     }
     
     // Result
     document.getElementById( "result" ).innerHTML = tp ;
     
 }
 
 function hideDelivDesc () {
 	$('tr.descr_class').css('visibility', 'hidden') ;
	$('div.delivery_way').css('margin', '0') ;
	$('div.delivery_way').css('padding', '0') ;
	$('div.delivery_way').css('height', '1px') ;

	
 }
 
 
 /*
 function changePersonalData () {
 	var elements = getElementsByClassName('value') ;
	for( i = 0 ; i < elements.length ; i++ ) {
		elements[i].style = 'color:red' ;
	}
 }


function check_agreem() {
	if ( $("#agreement").attr("checked") ){
		xajax_make_order() ;
	} else {
		if (confirm("Принять пользовательское соглашение?")) {
			xajax_make_order() ;
		} else {
			void('null') ;
		}
		 
	}
}

function check_agreem() {
	
		xajax_make_order() ;
	
}
*/

