var cssFix = function()
{
    var u = navigator.userAgent.toLowerCase(),
    addClass = function(el,val)
    {
        if(!el.className)
        {
            el.className = val;
        }
        else
        {
            var newCl = el.className;
            newCl += (" "+val);
            el.className = newCl;
        }
    },
    is = function(t){return (u.indexOf(t)!=-1)};
    addClass(document.getElementsByTagName('html')[0],[
        (!(/opera|webtv/i.test(u))&&/msie (\d)/.test(u)) ? ('ie ie'+RegExp.$1)
        :is('firefox/2') ? 'gecko ff2'
        :is('firefox/3.5') ? 'gecko ff35'
        :is('firefox/3') ? 'gecko ff3'
        :is('gecko/') ? 'gecko'
        :is('opera/9') ? 'opera opera9':/opera (\d)/.test(u)?'opera opera' + RegExp.$1
        :is('konqueror') ? 'konqueror'
        :is('applewebkit/') ? 'webkit safari'
        :is('mozilla/') ? 'gecko':'',
        (is('x11') || is('linux')) ? ' linux'
        :is('mac') ? ' mac'
        :is('win') ? ' win':''
    ].join(" "));
}();

$.fn.wait = function(time, type)
{
    time = time || 3000;
    type = type || "fx";
    return this.queue(type, function()
    {
        var self = this;
        setTimeout(function() {$(self).dequeue();}, time);
    });
};

var wait = '<span class="catalogWaitInside">Пожалуйста, подождите<img class="spinner" src="/images/spinner.gif" align="right" /></span>';
var preloader = '<div style="width:100px; height:100px; background:url(/img/loader.gif) no-repeat; display:none; text-align:center;"></div>';

$(function()
{
    $("div.filter a#filter_link").click(function()
    {
		var filterHead = $(this).parent().get(0);
		var filterBlock = $(filterHead).parent().get(0);
		var filterForm = $(filterBlock).children().get(1);
		var filterBody = $(filterForm).children().get(0);
		var fbodyDis = $(filterBody).css("display");
		if(fbodyDis=="block")
        {
		    $(filterBody).hide();
			$("div.bottomFilter").css('display', 'none');
			$(filterHead).css("border", "0");
			$(this).removeClass('active');
			$(filterBlock).css('background', 'none');
			$(filterBlock).find("div.rightBackground").css('background', 'none');
		}
        else
        {
			$(filterBody).show();
			$("div.bottomFilter").css('display', 'block');
			$(filterHead).css("border", "1px solid #ccc");
			$(filterHead).css("border-bottom", "0");
			$(this).addClass('active');
			$(filterBlock).css('background', 'url(/img/popup_right.png) repeat-y right top');
			$(filterBlock).find("div.rightBackground").css('background', 'url(/img/popup_right.png) repeat-y right top');
		}
		return false;
    });
});

function setFinalSumm(noVariation)
{
	if(noVariation == false)
	{
		var inputs = $('div.variant_area input.article_count');
		var finalSumm = 0;
		var orderHTML = '';
		for(var i = 0; i < inputs.length; i++)
        {
			if($(inputs[i]).val() > -1)
            {
				var count = $(inputs[i]).val();
				var name =  $(inputs[i]).attr('name');	
				var artCut = name.split('_');
				var art = artCut[1];
				var price = $('div.variant_area input[name=price_' + art + ']').val();
				finalSumm = finalSumm + (price * count);
				$('span.variant_count').html(finalSumm);
				if(count>0)
                {
					var productId = $('input[name=product_id_' + art + ']').val();
					var currency = $('input[name=currency_' + art + ']').val();
					var name = $('input[name=name_' + art + ']').val();
					//alert(productId+' '+currency+' '+name);
					orderHTML += '<input type="hidden" name="PRODUCT_ID[' + art + ']" value="' + productId + '"><input type="hidden" name="PRICE[' + art + ']" value="' + price + '"><input type="hidden" name="CURRENCY[' + art + ']" value="' + currency + '"><input type="hidden" name="WEIGHT[' + art + ']" value="0"><input type="hidden" name="QUANTITY[' + art + ']" value="' + count + '"><input type="hidden" name="NAME[' + art + ']" value="' + name + '"><input type="hidden" name="ARTICUL[' + art + ']" value="' + art + '">';
					$('span.num'+art).html(count);
					$('td.block'+art).css('visibility', 'visible');
					//$('td.block'+art).css('float', 'left');
					$('td.block'+art).css('padding-right', '10px');
				//alert(orderHTML);
				} else {$('td.block'+art).css('visibility', 'hidden');}
			}
		}
		if(finalSumm == 0)
        {
			$('input[name=stay_order]').css('display', 'none');	
		}
        else
        {
			//alert(orderHTML);
			$('div.order_content').html(orderHTML);
			$('input[name=stay_order]').css('display', 'block');	
		}
	}
	else // страница с рукой
	{
		var count = $('div.art_count input[name=count]').val();
		if (count == 0)
		{
			$('div.art_count input[name=count]').val(1)
		}
	}
}

$(function()
{
    $("div.art_count a.count_plus").click(function()
    {
		var filterHead = $(this).parent().get(0);
		var fieldCount = $(filterHead).find('input.article_count');
		var fieldVal = $(fieldCount).val();
		fieldVal++;
		$(fieldCount).val(fieldVal);
		if($(this).attr('class').indexOf('in_detail_card') !== -1)
		{
			setFinalSumm(false);
		}
		else
		{
			setFinalSumm();
		}
		return false;
    });
});

$(function()
{
    $("div.art_count a.count_minus").click(function()
    {
		var filterHead = $(this).parent().get(0);
		var fieldCount = $(filterHead).find('input.article_count');
		var fieldVal = $(fieldCount).val();
		fieldVal--;
		if(fieldVal>-1) {
		$(fieldCount).val(fieldVal);
		}
		if($(this).attr('class').indexOf('in_detail_card') !== -1)
		{
			setFinalSumm(false);
		}
		else
		{
			setFinalSumm();
		}
		return false;
    });
});


$(function()
{
    $("form#addToBasket").submit(function()
    {
        var children = $(this).find("input[type=hidden]");
        var str = '';
        for(var i=0; i < children.length; i++)
        {
            if(i > 0) str += '&';
            str += $(children[i]).attr('name') + "=" + $(children[i]).val();
        }
        if(str.length > 0)
        {
            $("div.basketWait").css('display', 'block');
            var subButton = $(this).find("input[type=submit]");
            $(subButton).css('display', 'none');
            $.ajax(
            {
                url: "/add_to_basket.php?page_template=empty",
                type: "POST",
                data: str,
                cache: false,
                success: function(html)
                {
                    var codeArr = html.split('<div id="basketSumm">');
                    var codeArr2 = codeArr[1].split('</div>');
                    var basketSumm = codeArr2[0];
                    var codeArr = html.split('<div id="basketCount">');
                    var codeArr2 = codeArr[1].split('</div>');
                    var basketCount = codeArr2[0];
                    $("#numTovar").html(basketCount);
                    $("#priceTovar").html(basketSumm);
                    $("div.basketWait").css('display', 'none');
                    $("a[rel=#tovarDob]").click();
                    $(subButton).css('display', 'block');
                }
            });
        }
        return false;
    });
});

$(function()
{
    $("form#ajaxRegister").submit(function()
    {
        var children = $(this).find("input");
		var auth = $(this).find("input#auth");
		var str = '';
        for(var i = 0; i < children.length; i++)
        {
            if(i > 0) str += '&';
            str += $(children[i]).attr('name')+"="+$(children[i]).val();	
        }
        if(str.length > 0)
        {
            $.ajax(
            {
                url: "/basket/?page_template=empty",
                type: "POST",
                data: str,
                cache: false,
                success: function(html)
                {
					//alert(auth.length);
					//if(auth.length > 0) location.href = '/cabinet/execution/delivery/';
                    $('input[name=BasketOrder]').click();
                }
            });
        }
        return false;
    });
});

function setMultiUrl(application)
{
	var str = '';
	if(application !== '')
    {
		var str = str + application + '/';
	}
	if($('select[name=pre]').length > 0)
    {
        var pre = $('select[name=pre]').val();
        if(pre !== '0') var str = str+pre+'/';
	}
	if($('select[name=type]').length > 0)
    {
        var type = $('select[name=type]').val();
        if(type !== '0') var str = str + type + '/';
	}
	if($('select[name=brand_name]').length > 0)
    {
        var brand = $('select[name=brand_name]').val();
        if (brand !== '0') var str = str +brand+'/';
	}
	if(str !== '' && str !== application + '/')
    {
		$('div.basketWait').css('display', 'block');
		$('div.basketWait').css('margin', '4px 0px 20px');
		var wait = $('div.basketWait').html();
		var str = '/catalog/' + str;
        $("div.catalog_content").html(wait);
		$.ajax(
        {
			url: str + 'index?page_template=empty&no_filter=yes',//"/add_to_basket.php?page_template=empty",
			type: "POST",
			data: '',
			cache: false,
			success: function(html)
            {
				/*var codeArr = html.split('<div id="catalog_content">');
				var codeArr2 = codeArr[1].split('</div>');
				var codeVal = codeArr2[0];
				alert(codeVal);*/
				$("div.catalog_content").html(html);
			}
		});
	}
}

/*
функция для перезагрузки каталога
current - массив с текущими значениями
change - массив со значениями, которые изменились
*/
function CatalogReload(current, change)
{
	var str = '';
	if(typeof change['application'] != "undefined" && change['application'].length > 0) var str = str + change['application'] + '/';
    else if(typeof current['application'] != "undefined" && current['application'].length > 0) var str = str + current['application'] + '/';
	if(typeof change['prescription'] != "undefined" && change['prescription'].length > 0) var str = str + change['prescription'] + '/';
    else if(typeof current['prescription'] != "undefined" && current['prescription'].length > 0) var str = str + current['prescription'] + '/';
	if(typeof change['type'] != "undefined" && change['type'].length > 0) var str = str + change['type'] + '/';
    else if(typeof current['type'] != "undefined" && current['type'].length > 0) var str = str + current['type'] + '/';
	if(typeof change['brand'] != "undefined" && change['brand'].length > 0) var str = str + change['brand'] + '/';
    else if(typeof current['brand'] != "undefined" && current['brand'].length > 0) var str = str + current['brand'] + '/';
	if(typeof change['collection'] != "undefined" && change['collection'].length > 0) var str = str + 'coll' + change['collection'] + '/';
    else if(typeof current['collection'] != "undefined" && current['collection'].length > 0) var str = str + 'coll' + current['collection'] + '/';
	if(typeof change['page'] != "undefined" && change['page'].length > 0) var str = str + 'page-' + change['page'] + '/';
    else if(typeof current['page'] != "undefined" && current['page'].length > 0) var str = str + 'page-' + current['page'] + '/';    
	if(typeof change['order_by'] != "undefined" && change['order_by'].length > 0) var str = str + 'order-' + change['order_by'] + '-' + change['order_type'] + '/';
    else if(typeof current['order_by'] != "undefined" && current['order_by'].length > 0) var str = str + 'order-' + current['order_by'] + '-' + current['order_type'] + '/';
	if(str !== '')
    {
        var wait = '<span class="catalogWaitInside">Пожалуйста, подождите<img class="spinner" src="/images/spinner.gif" align="right" /></span>';
		var str = '/catalog/' + str;
        $("div.catalog_content").html(wait);
        $("div.catalog_content").load(str + 'index?page_template=empty&no_filter=yes', {}, function()
        {
            if(typeof change['page'] != "undefined" && change['page'].length > 0) document.location.href = "#page_" + change['page'];
        });
    }
}

// функция выполняет перезагрузку раздела каталога (облегченная версия). Необходимо передавать готовый URL, но без get-параметров.
function CatalogReloadLight(url, set_anchor)
{
    $('html, body').css('overflow','hidden');
    $.blockUI(
    {
        message:$(preloader),
        css:
        {
            width:'100px',
            height:'100px',
            left:'45%',
            border:'none',
            cursor:'default',
            background:'transparent'
        },
        overlayCSS:
        {
            cursor:'default'
        }
    });
	//$("div.catalog_content").html(wait);
/*
    var params = '';
    if($('#selected-barand').length > 0)
    {
        var selected_brand = $('#selected-barand').val();
        if(!empty(selected_brand)) params = '&brand=' + selected_brand;
    }
//*/
	if($('#i-stored-hash').length > 0 && set_anchor.length > 0) $('#i-stored-hash').val('/' + set_anchor + '/');
	if(set_anchor.length > 0) document.location.href = "#/" + set_anchor + "/";
	$('.bottom-opinions').remove();
	$("div.catalog_content").load(url + '?page_template=empty&no_filter=yes', {}, function ()
	{
		var opinions = $('.bottom-opinions').clone(true);
		opinions.insertAfter('.text_content_top');
		$('body').find('.catalog_content .bottom-opinions').remove();
		if($('body').find('.bottom-opinions').length > 1) $('body').find('.bottom-opinions').eq(1).remove();
        $('html, body').css('overflow','auto');
        $.unblockUI();
	});	
	return false;
}

/*
функция выполняет перезагрузку раздела каталога
url - необходимая страница для загрузки
params - параметры для передачи в строке запроса
set_anchor - установка анкора
*/
function CatalogReloadByParams(url, params, set_anchor)
{
    $('html, body').css('overflow','hidden');
    $.blockUI(
    {
        message:$(preloader),
        css:
        {
            width:'100px',
            height:'100px',
            left:'45%',
            border:'none',
            cursor:'default',
            background:'transparent'
        },
        overlayCSS:
        {
            cursor:'default'
        }
    });
	if($('#i-stored-hash').length > 0 && set_anchor.length > 0) $('#i-stored-hash').val('/' + set_anchor + '/');
	if(set_anchor.length > 0) document.location.href = "#/" + set_anchor + "/";
	$('.bottom-opinions').remove();
	$("div.catalog_content").load(url + '?page_template=empty&no_filter=yes' + params, {}, function()
	{
		var opinions = $('.bottom-opinions').clone(true);
		opinions.insertAfter('.text_content_top');
		$('body').find('.catalog_content .bottom-opinions').remove();
		if($('body').find('.bottom-opinions').length > 1) $('body').find('.bottom-opinions').eq(1).remove();
        $('html, body').css('overflow','auto');
        $.unblockUI();
	});
	return false;
}

function OpinionsNextPage(product_id, page)
{
    var wait = '<span class="catalogWaitInside">Пожалуйста, подождите<img class="spinner" src="/images/spinner.gif" align="right" /></span>';
    $("div#opinions_list").html(wait);
    $("div#opinions_list").load('/ajax/ajax.php?page_template=empty&opn_page=' + page + '&id=' + product_id);
}

function QuestionsNextPage(product_id, page, consult_id)
{
    document.location.href = "#to_page";
    setTimeout('move_to_q()', 200);
    var wait = '<span class="catalogWaitInside">Пожалуйста, подождите<img class="spinner" src="/images/spinner.gif" align="right" /></span>';
    $("div#questions_list").html(wait);
    $("div#questions_list").load('/ajax/ajax_q.php?page_template=empty&q_page='+page+'&id='+product_id+'&consultation_id'+consult_id);    
}

function LoadContent(params)
{
    $(params.div).load('/ajax/content-loader.php?page_template=empty&content=' + params.content + '&' + params.pagename + '=' + params.pagenum + '&id=' + params.pid);
}

function move_to_q()
{
    document.location.href = "#faq";
}

$(function()
{
    $("div.request_to_order form").submit(function()
    {
        if($("div.request_to_order form div#requestAccess").length == 0)
        {
			var requestAccess = $("div#requestAccess").html();
			var requestError = $("div#requestError").html();
			$("div#requestAccess").insertAfter("div.attention");
			$("div#requestError").insertAfter("div.attention");
			$("div#requestAccess").html(requestAccess);
			$("div#requestError").html(requestError);
		}
        var idForm = $("div.request_to_order input[name=idForm]").val();
        var prodId = $("div.request_to_order input[name=product_id]").val();
        var hideChild = $(this).find("input[type=hidden]");
        var lastChild = $(hideChild).get(hideChild.length-1);
        $(lastChild).val(prodId);
        var children = $(this).find("input");
        var str = 'id_form='+idForm+'&';
        for(var i = 0; i < children.length; i++)
        {
            if(i > 0) str += '&';
            str += $(children[i]).attr('name') + "=" + $(children[i]).val();
        }
        if($("div.request_to_order form input[type=text]").val() == '')
        {
            $("div#requestError").css('display', 'block');
            $("div#requestAccess").css('display', 'none');
        }
        else
        {
            var subButton = $(this).find("input[type=submit]");
            $(subButton).css('display', 'none');
            $("div.basketWait").css('display', 'block');
            if(str.length > 0)
            {
                $.ajax(
                {
                    url: "/send_request.php?",
                    type: "POST",
                    data: str,
                    cache: false,
                    success: function(html)
                    {
						$("div#requestAccess").css('display', 'block');
						$("div#requestError").css('display', 'none');
						$("div.request_to_order form input[type=text]").val('');
                        $("div.basketWait").css('display', 'none');
                        $(subButton).css('display', 'block');
                    }
                });
            }
        }
        return false;
    });
});


$(document).ready(function()
{
    $.ajaxSetup(
    {
        beforeSend: function(request)
        {
            request.setRequestHeader('Accept', 'application/html+ajax');
        }
    });

	$('a#qr-code').click(function()
	{
		var contacts = $('.contacts');
		$.blockUI(
		{
			message:contacts,
			css:
			{
				top:($(window).height() - contacts.outerHeight(true))/2,
				left:($(window).width() - contacts.outerWidth(true))/2,
				border:'none',
				cursor:'default',
				background:'transparent'
			},
			overlayCSS:
			{
				cursor:'default'
			}
		});
	});
	
	$('#close').click($.unblockUI);
	
});

// Аналог php функции substr
function substr(f_string, f_start, f_length)
{    // Return part of a string
    if(f_start < 0) f_start += f_string.length; 
    if(f_length == undefined) f_length = f_string.length;
    else if(f_length < 0) f_length += f_string.length;
    else f_length += f_start;
    if(f_length < f_start) f_length = f_start;
    return f_string.substring(f_start, f_length);
}


function get_anchor()
{
    var URL = document.location.toString().split('#');
    if(URL.length > 1) return URL[1];
    else return '';
}

Cookie =
{
    isSupported: function()
    {
        return !!navigator.cookieEnabled;
    },
    exists: function(name)
    {
        return document.cookie.indexOf(name + "=") + 1;
    },
    write: function(name, value, expires, path, domain, secure)
    {
        expires instanceof Date ? expires = expires.toGMTString() : typeof(expires) == 'number' && (expires = (new Date(expires * 1e3)).toGMTString());
        var r = [name + "=" + escape(value)], s, i;
        for(i in s = {expires: expires, path: path, domain: domain}) s[i] && r.push(i + "=" + s[i]);
        return secure && r.push("secure"), document.cookie = r.join(";"), true;
    },
    read: function(name)
    {
        var c = document.cookie, s = this.exists(name), e;
        return s ? unescape(c.substring(s += name.length, (c.indexOf(";", s) + 1 || c.length + 1) - 1)) : "";
    },
    remove: function(name, path, domain)
    {
        return this.exists(name) && this.write(name, "", new Date(0), path, domain);
    }
};

function setCookie(name, value, expires, path, domain, secure)
{
    document.cookie = name + "=" + escape(value) + ((expires) ? "; expires=" + expires : "") + ((path) ? "; path=" + path : "") + ((domain) ? "; domain=" + domain : "") + ((secure) ? "; secure" : "");
}

function getCookie(name)
{
	var cookie = " " + document.cookie;
	var search = " " + name + "=";
	var setStr = null;
	var offset = 0;
	var end = 0;
	if(cookie.length > 0)
    {
		offset = cookie.indexOf(search);
		if(offset != -1)
        {
			offset += search.length;
			end = cookie.indexOf(";", offset)
			if(end == -1) end = cookie.length;
			setStr = unescape(cookie.substring(offset, end));
		}
	}
	return(setStr);
}

/* аналог PHP-функции intval */
function intval(mixed_var, base)
{
    var type = typeof(mixed_var);
    if(type === 'boolean')
    {
        return (mixed_var) ? 1 : 0;
    }
    else if(type === 'string')
    {
        tmp = parseInt(mixed_var, base || 10);
        return (isNaN(tmp) || !isFinite(tmp)) ? 0 : tmp;
    }
    else if(type === 'number' && isFinite(mixed_var))
    {
        return Math.floor(mixed_var);
    }
    else
    {
        return 0;
    }
}

/* аналог PHP-функции str_replace */
function str_replace(search, replace, subject, count)
{
    j = 0,
    temp = '',
    repl = '',
    sl = 0,
    fl = 0,
    f = [].concat(search),
    r = [].concat(replace),
    s = subject,
    ra = r instanceof Array,        sa = s instanceof Array;
    s = [].concat(s);
    if(count) this.window[count] = 0; 
    for(i = 0, sl = s.length; i < sl; i++)
    {
        if(s[i] === '') continue;
        for(j = 0, fl = f.length; j < fl; j++)
        {
            temp = s[i] + '';
            repl = ra ? (r[j] !== undefined ? r[j] : '') : r[0];
            s[i] = (temp).split(f[j]).join(repl);
            if(count && s[i] !== temp) this.window[count] += (temp.length - s[i].length) / f[j].length;
        }
    }
    return sa ? s : s[0];
}

/* аналог PHP-функции is_array */
function is_array(mixed_var)
{
    var _getFuncName = function(fn)
    {
        var name = (/\W*function\s+([\w\$]+)\s*\(/).exec(fn);
        if (!name)
        {
            return '(Anonymous)';
        }
        return name[1];
    },
    _isArray = function(mixed_var)
    {
        return Object.prototype.toString.call(mixed_var) === '[object Array]';
    };
    if(!mixed_var || typeof mixed_var !== 'object')
    {
        return false;
    }
    this.php_js = this.php_js || {};
    this.php_js.ini = this.php_js.ini || {};
    var ini = this.php_js.ini['phpjs.objectsAsArrays'];
    return _isArray(mixed_var) || (!ini || ((parseInt(ini.local_value, 10) !== 0 && (!ini.local_value.toLowerCase || ini.local_value.toLowerCase() !== 'off')))) && (Object.prototype.toString.call(mixed_var) === '[object Object]' && _getFuncName(mixed_var.constructor) === 'Object');
}

/* аналог PHP-функции empty */
function empty(mixed_var)
{
	var key;    
	if(mixed_var === "" || mixed_var === 0 || mixed_var === "0" || mixed_var === null || mixed_var === false || typeof mixed_var === 'undefined') {return true;}
	if(typeof mixed_var == 'object')
	{
		for(key in mixed_var) {return false;}
		return true;
	}
	return false;
}

/* аналог PHP-функции mktime */
function mktime()
{
    var d = new Date(), r = arguments, i = 0, e = ['Hours', 'Minutes', 'Seconds', 'Month', 'Date', 'FullYear'];
    for(i = 0; i < e.length; i++)
    {
        if(typeof r[i] === 'undefined')
        {
            r[i] = d['get' + e[i]]();
            r[i] += (i === 3); // +1 to fix JS months.
        }
        else
        {
            r[i] = parseInt(r[i], 10);
            if(isNaN(r[i])) return false;
        }
    }
    r[5] += (r[5] >= 0 ? (r[5] <= 69 ? 2e3 : (r[5] <= 100 ? 1900 : 0)) : 0); 
    d.setFullYear(r[5], r[3] - 1, r[4]);
    d.setHours(r[0], r[1], r[2]);
}

function function_exists(func_name)
{
    if(typeof func_name === 'string') func_name = this.window[func_name];
    return typeof func_name === 'function';
}
