(function($) {
	$.fn.sres = function(options) {
		options = $.extend({
			z: 100,
			chars: 3,
			timeout: 5000,
			url: 'index.php',
			div: '#viewresult'
		}, options);
		options.chars = options.chars < 1 ? 1 : options.chars;
		options.timeout = options.timeout < 100 ? 100 : options.timeout;
		options.url = options.url == '' ? location.href : options.url;
		var input_id = this;
		$(this).attr('autocomplete', 'off');
		var loading = '<img src="/design/user/images/searchresult_bg.png" class="bg"><div style="padding:15px 15px 0 15px;"><img src="/design/user/images/ajax.gif" alt="" align="absmiddle" /> Выполняется быстрый поиск</div>';
		var result_div = $(options.div);		
		var search_input = false;
		var search_result = false;
		var search_timer = null;
		var input_timer = null;
		function search_result_check()
		{
			$(result_div).css( 'display' , 'none' );
			clearTimeout(search_timer);
		}
		$(this).bind("keyup", function(e){
            var s = input_id.val();
            $(result_div).show();
   			$(result_div).html(loading);
			if (s.length < options.chars)
			{
				$(result_div).hide();
				return;
			}
   			clearTimeout(input_timer);
			input_timer = setTimeout(function() {
				if (e.type == 'focus')
				{
					search_input = true;
					clearTimeout(search_timer);
				}
				function onAjaxSuccess(data)
				{
					if (data.length == 0)
					{
						$(result_div).css( 'display' , 'none' );
					} else {
						$(result_div).html( data );
						$(result_div).css( 'display' , 'block' );
					}
				}
				$.get(
					options.url, {
						s : s,
						category_id : $("#filter_by_category").val()
					}, onAjaxSuccess
				);
			}, 200);
		});
		$(this).bind("blur", function() {
			search_input = false;
			if (!search_result)
			{
				search_timer = setTimeout(function() {
					search_result_check();
				}, options.timeout);
			}
		});
		$(this).bind("focus", function() {
			search_input = true;
			clearTimeout(search_timer);
		});
		$(this).bind("mouseenter", function() {
			return false;
		});
		$(result_div).bind("mouseenter", function() {
			search_result = true;
			clearTimeout(search_timer);
		});
		$(result_div).bind("mouseleave", function() {
			search_result = false;
			if (!search_input)
			{
				search_timer = setTimeout(function() {
					search_result_check();
				}, options.timeout);
			}
		});
	}
})(jQuery);

function showTab(id){
	for(i=1;i<6;i++){
		el = document.getElementById('tab'+i);
		if(el){
			el.className = (id==i ? 'span' : 'nospan');
		}
		el = document.getElementById('bl'+i);
		if(el){
			el.style.display = (id==i ? 'inline' : 'none');
		}
		el = document.getElementById('br'+i);
		if(el){
			el.style.display = (id==i ? 'inline' : 'none');
		}
		el = document.getElementById('tabContent'+i);
		if(el){
			el.style.display = (id==i ? 'block' : 'none');
		}
	}
	return false;
}
function ce (tagName) {	return document.createElement(tagName) }
galwin = 0;
function openWindow( winvar, url, name, width, height )
{
url = unescape(url);
window.open( url, "_blank", 'toolbar=0,status=0,resizable=0,scrollbars=1,width='+width+',height='+height );
}
function showDir( width, height, url )
{
   w=width;
   h=height;
   if (w>screen.width) w=screen.width*0.75;
   if (h>screen.height) h=screen.height*0.75;
   openWindow(galwin, url, "showgal", w, h);
}
winvar = 0;
function popup()
{
winvar = open( '', 'wishwin', 'toolbar=0,status=0,resizable=0,scrollbars=0,width=300,height=150' );
}

    function setX() {
        document.getElementById('axcrt').style.pixelTop = document.body.scrollTop + Math.ceil((document.body.clientHeight-100)/2);
    }

    var agt = navigator.userAgent.toLowerCase();
    var is_ie = (agt.indexOf("ie") != -1);
    var width=540,height=334;
  	if(self.innerWidth && self.innerHeight) { // Mozilla, Firefox etc
    	width=self.innerWidth;
    	height=self.innerHeight ;
  	} else if (document.body){ // MS IE
	    width=document.body.clientWidth;
	    height=document.body.clientHeight;
  	}
    iebag = ( is_ie ) ? 'absolute' : 'fixed';
    document.write('<div id="axcrt" style="background: none repeat scroll 0% 0% #bfd1da; border: 1px dotted rgb(203, 203, 203); position: ' + iebag + '; display: none; visibility: hidden; z-index: 100; left: '+Math.ceil((width-300)/2)+'px; top: '+Math.ceil((height-100)/2)+'px; width: 400px; height: 40px;"><table border="0" cellpadding="0" cellspacing="0" width="100%" height="100%"><tr><td style="text-align: center; vertical-align: middle;"><div id="axcrt_text">Идет добавление товара в корзину...</div></td></tr></table></div>');
    if ( is_ie ) {
        window.onscroll = setX;
    }
    
function setModels(chooser) {
    var modelChooser = chooser.form.elements["model_id"];
    // empty previous settings
    modelChooser.options.length = 0;
    // get chosen value to act as index to modeldb hash table
   	modelChooser.options[0] = new Option("Загрузка...", "0", true, false);
    var choice = chooser.options[chooser.selectedIndex].value;
    JsHttpRequest.query(
    '/ajax/model_loader.php',
    {
        'man_id': choice,
        'bugfix': "yes"
	    },
	    function(result, errors) {
	    	if (!errors && result.array) {
				// insert default first item
			    modelChooser.options.length = 0;
			    modelChooser.options[0] = new Option("выберите ...", "0", true, false);
			        if (choice != "") {
				        // loop through array of the hash table entry, and populate options
				        for (var i = 0; i < result.array.length; i++) {
				            modelChooser.options[i + 1] = new Option(result.array[i].name, result.array[i].model_id);
				        }
				    }
	    	}
	    },
	    true
	);
}

function setDelivery(chooser,child_name,action) {
	var old_value = 0;
	if(child_name){
    	var modelChooser = chooser.form.elements[child_name];
		old_value = modelChooser.length ? modelChooser.options[modelChooser.selectedIndex].value : 0;
	    // empty previous settings
	    modelChooser.options.length = 0;
	    // get chosen value to act as index to modeldb hash table
	   	modelChooser.options[0] = new Option("Загрузка...", "0", true, false);
	}
    ///var choice = chooser.options[chooser.selectedIndex].value;
   	var choice = true;
    var region_id = $('#region_id').length ? $('#region_id').val() : $('#adr11').val();
    var city_id = $('#city_id').length ? $('#city_id').val() :  $('#adr13').val() 
    var delivery_method_id = $('#delivery_method_id').val();
    var payment_type_id = $('#payment_type_id').val();
    JsHttpRequest.query(
    '/ajax/delivery_form.php',
    {
        'action': action,
        'region_id':region_id,
        'city_id':city_id,
        'delivery_method_id':delivery_method_id,
        'payment_type_id':payment_type_id
	    },
	    function(result, errors) {
	    	if (!errors) {
	    		if(result.array){
					// insert default first item
					while(modelChooser.childNodes.length){
						if(modelChooser.firstChild.tagName=='OPTGROUP') while(modelChooser.firstChild.childNodes.length) modelChooser.firstChild.removeChild(modelChooser.firstChild.firstChild);
						modelChooser.removeChild(modelChooser.firstChild);
					}
		        	if(child_name == 'delivery_method_id'){
		        		delivery_cost_arr = {}
		        		delivery_descr_arr = {}
		        	}
		        	if(child_name == 'payment_type_id'){
		        		percent_discount_arr = {}
		        		payment_discount_arr = {}
			            if(delivery_method_id==1){ //Russian post
			            	if(result['shopping_cart_paid_categories']==0){
				            	$("#freedel").show();
			            	}
			            }
			            else
			            	$("#freedel").hide();
		        	}
				    //modelChooser.options[0] = new Option("выберите ...", "0", true, false);
					if (choice != "") { 
						// loop through array of the hash table entry, and populate options
						for (var i = 0; i < result.array.length; i++) {
							if(child_name == 'delivery_method_id'){
								delivery_cost_arr[result.array[i]['key']] = result.array[i]['delivery_rate'];
								delivery_descr_arr[result.array[i]['key']] = result.array[i]['description'];
							}
							if(child_name == 'payment_type_id'){
								payment_discount_arr[result.array[i]['key']] = result.array[i]['payment_discount'];
								percent_discount_arr[result.array[i]['key']] = result.array[i]['percent_discount'];
							}
							modelChooser.options[i] = new Option(result.array[i]['item'], result.array[i]['key'],false,(old_value==result.array[i]['key']));
						}
						if(child_name=='payment_type_id' && $("#payment_type_id option[value='5']")){
							$("#payment_type_id option[value='5']").remove();
							for(group in result.roboPayment){
								$(modelChooser).append($('<optgroup label="RoboKassa '+result.roboPayment[group]['description']+'"></optgroup>'));
								var roboChild=result.roboPayment[group]['items'];
								for(var itemqqq in roboChild){
									$(modelChooser).append($('<option value="5'+itemqqq+'">'+result.roboPayment[group]['items'][itemqqq]+'</option>'));
								}
							}
						}
				//		if($(modelChooser).attr("id")=="delivery_method_id") $("#delivery_method_id [value='"+dform_delivery_method_id+"']").attr("selected", "selected");
						if($(modelChooser).attr("id")=="payment_type_id"){
							$('#adressForm').bind('submit',function(){$(this).submit();});
						}
						if(child_name) $('#'+child_name).change();
					}
	    		}
		        if(child_name == ''){
	    		
		    		$("#sc_total").text(1*result["shopping_cart_price"] + 1*getSelectedDeliveryRate() + ' р');
		    		if(getSelectedPaymentDiscount()>0){
		    			// $("#discount").text(getSelectedPaymentDiscount() + ' р' );
		    			// $("#discount_percent").text(getSelectedPercentDiscount() + ' %' );
		    			// $("#discount_block").show();
		    		}else{
		    			$("#discount_block").hide();	    			
		    		}
		    		
		    			result["shopping_cart_price"] = 1*result["shopping_cart_price"] + 1*getSelectedDeliveryRate();
		    		$("#shopping_cart_total_amount").val(1*result["shopping_cart_price"]);
		    		$("#sc_total").text(1*result["shopping_cart_price"] + ' р');
            	
		        }
	    		
	    	}
	    },
	    true
	);
}
function getSelectedDeliveryRate(){
	//При перезагрузке контрола "Доставка" каждый раз пересоздается глобальный массив delivery_cost_arr,
	//который всегда содержит все доступыне методы доставки и их стоимость. Эта функция получает стоимость доставки для выбранного в селекте типа доставки.
	return delivery_cost_arr[$('#delivery_method_id').val()];
}
function getSelectedPaymentDiscount(){
	return payment_discount_arr[$('#payment_type_id').val()];	
}
function getSelectedPercentDiscount(){
	return percent_discount_arr[$('#payment_type_id').val()];	
}
function changeDeliveryDescr(){	
	$('#delivery_descr').html(delivery_descr_arr[$('#delivery_method_id').val()]);
}

function changeDeliveryRate(sum){
	sum = 1 * $("#shopping_cart_total_amount").val();
	//Функция меняет блок "Итого с доставкой" при изменени метода доставки.
	if(1*getSelectedDeliveryRate()==0){
    	$('#delivery_cost_notice').hide();
    	$('#free_del').show();
    	$('#not_free_del').hide();
		
	}else{
		$('#delivery_cost_notice').show();
		$('#free_del').hide();
		$('#not_free_del').show();		
	}
	$('#delivery_cost').text(getSelectedDeliveryRate() + ' р');
}
function checkModelForm(chooser) {
	var model = chooser.form.elements["model_id"];
	if ( model.selectedIndex !=-1 )
		{
			if (model.options[model.selectedIndex].value>0) {
  				return true;
			} else {
				alert("Вы не выбрали модель телефона");
				return false;
			}
		}
		else 
		{
			alert("Вы не выбрали модель телефона");
			return false;
		}
}

hs.graphicsDir = '/design/user/images/';
hs.outlineType = 'rounded';
hs.loadingOpacity = 1;

hs.restoreTitle = 'Нажмите на картинку, чтобы закрыть окно';
hs.loadingText = 'Загрузка...';
hs.loadingTitle = 'Отменить загрузку';
hs.focusTitle = 'Нажмите для возврата к картинке';
hs.fullExpandTitle = 'Развернуть во всю величину';


// Jquery UI
$(document).ready(function() {
	
	$('.account_tabs2').click(function() {
		$('#step2_login').show();
		$('#step2_reg').hide();
		return false;
	});
	$('.account_tabs1').click(function() {
		$('#step2_login').hide();
		$('#step2_reg').show();
		return false;
	});
    $("input#search_product").sres({
			"url": "/ajax/search_help.php"
		}
	);
	$('ul.tabs').delegate('li:not(.current)', 'click', function() {
		$(this).addClass('current').siblings().removeClass('current')
			.parents('div.section').find('div.box').hide().eq($(this).index()).fadeIn(150);
		var query = $("#search_product").val();
		if ($('#filter_by_category').val() != $(this).attr("value") &&  query != 'Поиск по сайту' && query.length > 2) {
		    var result_div = $("#viewresult");
			function onAjaxSuccess(data)
				{
					if (data.length == 0)
					{
						$(result_div).css( 'display' , 'none' );
					} else {
						$(result_div).html( data );
						$(result_div).css( 'display' , 'block' );
					}
				}
				$.get(
					"/ajax/search_help.php", {
						s : $("#search_product").val(),
						category_id : $(this).attr("value")
					}, onAjaxSuccess
				);
		}
		$('#filter_by_category').val($(this).attr("value"));
	})
	$('#callback').click(function() {
		$('#callback_div').toggle('fast');
	});
	$('#do_callback').click(function(){
		var form = $('#callback_form');
		if (form.children('input[name=phone]').val())
		{
		form.children('#comment').text('Подождите... Запрос отправляется...');
    	jQuery.ajax({
		  type: "POST",
		  url: "/ajax/callback.php",
		  dataType: "json",
		  data: "phone=" + form.children('input[name=phone]').val() + "&text=" + form.children('textarea[name=text]').val() + "&cbh=" + Math.random()*100000,
		  success: function(response){
		  	if (response.status == 'ok') {
		  		form.children('#comment').text(response.text);
		  		form.children('#comment').attr('class', 'good');
		  		setTimeout(function() { $('#callback_div').toggle('fast'); }, 5000);
		  	} else {
		  		form.children('#comment').text(response.text);
		  		form.children('#comment').attr('class', 'error');
		  	}
		  },
		  error: function(){
		  		form.children('#comment').attr('class', 'error');
				form.children('#comment').text('Неизвестная ошибка');
		 }
    	});
		} else {
			form.children('#comment').text('Вы не ввели номер телефона');
			form.children('#comment').attr('class', 'error');
		}
    	return false;
	});
 	$.mask.definitions['0']=$.mask.definitions['9'];
 	$.mask.definitions['9']='';
 	
	$('.phone_input').mask("+7 (900) 0000000", {completed:function(){
			console.log(this.val());
	}});	
});

function showadvice(id){
		el = document.getElementById(id);
		if(el.style.display == 'none'){
			el.style.display = 'block';
		}
		else {
			el.style.display = 'none';
		}
	}
