
var lang='';

function confirm_delete() {
    return (window.confirm('Вы действительно хотите удалить этот товар?'));
    }


//скрипт изменения цвета
/*
var ccol=1;

function ch_col() {
    
    obj=document.getElementById('corp_cl');
    
    if (obj) {
        if (ccol) {
            obj.style.color='#FFFFFF';
            ccol=0;
            setTimeout("ch_col()", 500);
        }
        else {
            obj.style.color='#790000';
            ccol=1;
            setTimeout("ch_col()", 200);
        }
    }
    

}

*/

function show_contact_window(lang) {
    if (lang=='ru' || lang=='ua') {
        $('#bottom_call').html('Все заказы принимаются через вебсайт.<br />Воспользуйтесь альтернативными контактам:<br />(044) 561 80 50<br />(093) 827 73 27<br /><br /><a href="http://www.providesupport.com?messenger=uaflowers"><img src="http://image.providesupport.com/image/uaflowers/online-1214617822.gif" /></a><br /><br /><a href="/ru/41/4">написать директору</a><br />');
    } else {
        $('#bottom_call').html('Use alternate phones:<br />(044) 561 80 50<br />(093) 827 73 27<br /><br /><a href="http://www.providesupport.com?messenger=uaflowers"><img src="http://image.providesupport.com/image/uaflowers/online-1214617822.gif" /></a><br /><br /><a href="/en/41/4">contact director</a><br />');
    }

    
/*    myWin= open("", "displayWindow", 
    "width=500,height=230,status=no,toolbar=no,menubar=no");
    
    myWin.document.open();
    
    myWin.document.write("<html><head><title>Не можете дозвониться?");
    myWin.document.write('</title><link href="http://www.ufl.ua/style.css" rel="stylesheet" type="text/css" /></head>');
    myWin.document.write('<body style="color:#555555; font-family:Tahoma,Verdana,Arial,sans-serif; font-size:12px;">');
    myWin.document.write("Все заказы принимаются через вебсайт.<br />Воспользуйтесь альтернативными контактам:<br /><br />(044) 561 80 50<br />(093) 827 73 27<br /><br />");
    myWin.document.write('<!-- BEGIN ProvideSupport.com Graphics Chat Button Code --><div id="ciBvBh" style="z-index:100;position:absolute"></div><div id="scBvBh" style="display:inline"></div><div id="sdBvBh" style="display:none"></div><script type="text/javascript">var seBvBh=document.createElement("script");seBvBh.type="text/javascript";seBvBh.defer=true;seBvBh.src=(location.protocol.indexOf("https")==0?"https://secure.providesupport.com/image":"http://image.providesupport.com")+"/js/uaflowers/safe-standard.js?ps_h=BvBh\u0026ps_t="+new Date().getTime();document.getElementById("sdBvBh").appendChild(seBvBh)</script><noscript><div style="display:inline"><a href="http://www.providesupport.com?messenger=uaflowers">Live Support</a></div></noscript><!-- END ProvideSupport.com Graphics Chat Button Code --><br /><br />');
    myWin.document.write('<a href="http://web.icq.com/whitepages/message_me/1,,,00.icq?uin=135355135&action=message"><img src="http://www.ufl.ua/images_new/icq_ico.gif" alt="" height="15" width="15" /></a> 135-355-135<br /><br />');
    myWin.document.write('<a href="skype:ufl.ua?call" title="Позвонить" style="text-decoration: none"><img vspace=2 src="http://www.ufl.ua/images_new/skype_ico.gif" alt="" height="16" width="16" /></a> ufl.ua<br /><br />');
    myWin.document.write("");
    myWin.document.write("</body></html>");

    myWin.document.close();  */

}

function showMess (text) {
    
    document.getElementById('mess_block').innerHTML=text;
    
    setOpacity();
}

var value = 0;
var posed = 0;
var messVisible=false;

function watchScroll() {
    if (messVisible) {
        var wdiv=document.getElementById('warning');
        
        var top=window.scrollY+(window.innerHeight/2)-30;
        top=parseInt(top);
        wdiv.style.top=top+'px';
        
        setTimeout("watchScroll()", 200);
    }
}

function setOpacity() {

    document.getElementById('message_block').style.display = "block";
    
    if (!posed) {
        var wdiv=document.getElementById("message_block");
        
        var pos_left=document.body.clientWidth/2;

        pos_left =pos_left - 250;

        pos_left=parseInt(pos_left);
        
        pos_left=pos_left+'px';
        wdiv.style.left=pos_left;

        var busyLayer = document.getElementById("shadow");

        if (window.innerHeight && window.scrollMaxY) {
            yScroll = window.innerHeight + window.scrollMaxY;
            var deff = document.documentElement;
            var hff = (deff&&deff.clientHeight) || document.body.clientHeight || window.innerHeight || self.innerHeight;
            yScroll -= (window.innerHeight - hff);
        } else if (document.body.scrollHeight > document.body.offsetHeight || document.body.scrollWidth > document.body.offsetWidth){
            yScroll = document.body.scrollHeight;
        } else {
            yScroll = document.body.offsetHeight;
        }

        if (busyLayer != null) {
            busyLayer.style.visibility = "visible";
            busyLayer.style.height = yScroll+'px';
        }
        alert(document.body.scrollHeight);
        var top=window.scrollY+(document.body.clientHeight/2)-30;
        top=parseInt(top);
        alert (top);
        wdiv.style.top=top+'px';

        posed=1;
        messVisible=true;
    }

    value += 1;
    var testObj = document.getElementById('shadow');

    testObj.style.width = "100%";
    //testObj.style.height = "100%";
    testObj.style.display = "block";
    testObj.style.opacity = value/10;
    testObj.style.filter = 'alpha(opacity=' + value*10 + ')';
    myTimeout = setTimeout("setOpacity()", 50);

    if (value >= 5) {
        clearTimeout(myTimeout);
    }
    
    
    watchScroll();
}

function removeOpacity() {
    value -= 1;
    var testObj = document.getElementById('shadow');

    myTimeout2 = setTimeout("removeOpacity()", 50);
    testObj.style.opacity = value/10;
    testObj.style.filter = 'alpha(opacity=' + value*10 + ')';

    if ((value/10) <= 0) {
        testObj.style.display = "none";
        clearTimeout(myTimeout2);
    }
    document.getElementById('message_block').style.display = "none";
    
    posed=0;
    messVisible=false;
}

function get_cities(country_id, city_id, selected_city, lang) {
    
    
    JsHttpRequest.query(
        'http://www.ufl.ua/ajax.php', // backend
        {
            'country_id': document.getElementById(country_id).value,
            'func' : 'get_cities',
            'lang' : lang
        },
        // Function is called when an answer arrives. 
        function(result, errors) {
            // Write the answer.
            
            if (result) {
                
                var cities=result["cities"];
                
                var city_field_obj=document.getElementById(city_id);
                
                for (i = city_field_obj.options.length; i >= 0; i--) {
                    city_field_obj.options[i] = null; 
                }
                
                var i=0;
                
                for (key in cities) {
                    if (selected_city==cities[key]['id']) city_field_obj.options[i] = new Option(cities[key]['name'], cities[key]['id'], true, true);
                    else city_field_obj.options[i] = new Option(cities[key]['name'], cities[key]['id']);
                    i++;
                }
            }
        },
        false  // do not disable caching
    );
}

function bottomGetAllCities(country_id, country_nick, act_city, lang, domain, country_name, country_link) {
    JsHttpRequest.query(
        'http://www.ufl.ua/ajax.php', // backend
        {
            'country_id': country_id,
            'func' : 'get_cities',
            'only_main' : '1',
            'lang' : lang
        },
        // Function is called when an answer arrives. 
        function(result, errors) {
            // Write the answer.
            
            if (result) {
                
                var cities=result["cities"];
                
                var cities_div=document.getElementById('bottom_cities');
                var cont='';
                
                for (key in cities) {
                    if (act_city==cities[key]['nick']) cont=cont+'<font color="Red">'+cities[key]['name']+'</font> | ';
                    else {
                        if (cities[key]['nick']=='other') cont=cont+'<a href="'+domain+lang+'/cveti-'+cities[key]['nick']+'-'+country_nick+'" title="'+cities[key]['name']+'">'+cities[key]['name']+'</a> | ';
                        else cont=cont+'<a href="'+domain+lang+'/cveti-'+cities[key]['nick']+'" title="'+cities[key]['name']+'">'+cities[key]['name']+'</a> | ';
                    }
                }
                
                if (lang=='ru') cont=cont+'<br /><a href="'+domain+lang+'/regions/'+country_link+'" style="color:red;"><b>Показать все города доставки в '+country_name+'...</b></a>';
                if (lang=='ua') cont=cont+'<br /><a href="'+domain+lang+'/regions/'+country_link+'" style="color:red;"><b>Показати усі міста доставки у '+country_name+'...</b></a>';
                if (lang=='en') cont=cont+'<br /><a href="'+domain+lang+'/regions/'+country_link+'" style="color:red;"><b>Show all delivery cities to '+country_name+'...</b></a>';
                
                cities_div.innerHTML=cont;
            }
        },
        false  // do not disable caching
    );
}

// функции для хоткиев

function hotkeys(e) {
  if (!e) e = window.event;
  var k = e.keyCode;
  
  if (e.ctrlKey) {
    if (k == 13) {
        
        $(function(){

            document.getElementById('pframe').src='http://www.ufl.ua/call_confirmation.html';

            // Dialog            
            $('#dialog').dialog({
                autoOpen: false,
                width: 300,
                buttons: {
                    "Закрыть": function() { 
                        $(this).dialog("close"); 
                    }
                }
            });
            
            
            $('#dialog').dialog("open"); 
            
            alert(div);
        });

        
    }
  }
}

function init() {
  document.onkeyup = hotkeys;
}

// обработка текстов для подмены Читать полностью

function init_read_full(id) {
    var obj=document.getElementById(id);
    obj.style.display = "none";
}

function replace_text(id) {
    var obj=document.getElementById(id);
    var obj2=document.getElementById(id+'_text');
    obj.innerHTML=obj2.innerHTML;
}

function show_other_prod(cat_id, lang) {
    JsHttpRequest.query(
        'http://www.ufl.ua/ajax.php', // backend
        {
            'func' : 'show_other_prod',
            'cat_id' : cat_id,
            'lang' : lang
        },
        // Function is called when an answer arrives. 
        function(result, errors) {
            // Write the answer.
            
            if (result) {
                
                var cities=result["cities"];
                
                var cities_div=document.getElementById('bottom_cities');
                var cont='';
                
                for (key in cities) {
                    if (act_city==cities[key]['nick']) cont=cont+'<font color="Red">'+cities[key]['name']+'</font> | ';
                    else {
                        if (cities[key]['nick']=='other') cont=cont+'<a href="'+domain+lang+'/cveti-'+cities[key]['nick']+'-'+country_nick+'" title="'+cities[key]['name']+'">'+cities[key]['name']+'</a> | ';
                        else cont=cont+'<a href="'+domain+lang+'/cveti-'+cities[key]['nick']+'" title="'+cities[key]['name']+'">'+cities[key]['name']+'</a> | ';
                    }
                }
                
                if (lang=='ru') cont=cont+'<br /><a href="'+domain+lang+'/regions/'+country_link+'" style="color:red;"><b>Показать все города доставки в '+country_name+'...</b></a>';
                if (lang=='ua') cont=cont+'<br /><a href="'+domain+lang+'/regions/'+country_link+'" style="color:red;"><b>Показати усі міста доставки у '+country_name+'...</b></a>';
                if (lang=='en') cont=cont+'<br /><a href="'+domain+lang+'/regions/'+country_link+'" style="color:red;"><b>Show all delivery cities to '+country_name+'...</b></a>';
                
                cities_div.innerHTML=cont;
            }
        },
        false  // do not disable caching
    );
}

/**
    
    Функции офф заказа

*/

// аякс отправка email

function ch_submit_email (email, lang, chpwd, password, remind_pwd) {
    
    if (document.location.href.indexOf("individual_order")==-1) {
        var ind_order=false;
    }
    else {
        var ind_order=true;
    }
    
    JsHttpRequest.query(
        '/ajax.php', // backend
        {
            'func' : 'submit_email',
            'email' : email,
            'lang' : lang,
            'chpwd' : chpwd,
            'password' : password,
            'remind_pwd' : remind_pwd,
            'ind_order' : ind_order
        },
        // Function is called when an answer arrives. 
        function(result, cont) {
            // Write the answer.
            
            if (result) {
                document.location.href=result['redirect'];
            }
            else {
                document.getElementById('checkout_container').innerHTML=cont;
            }
            
        },
        false  // do not disable caching
    );
}

// показываем подсказки

var timeoutId=false;

function showHelp (obj, show, text) {
    
    if (timeoutId) clearTimeout(timeoutId);
    
    if (show) {
        if (text!=false) {
            $("#help_block_cont").html(text);
        
            $("#help_block").css("left", $(obj).offset().left + $(obj).width()-5 );
            $("#help_block").css("top", $(obj).offset().top - 3);
        }
        
        $("#help_block").css("display", 'block');
        
        return true;
    }
    else {
        $("#help_block_cont").html('');
        $("#help_block").css("display", 'none');
        
        return true;
    }
}

// Мигающее предупреждение на главной

function blink(obj) {
    if (obj.style.color=='red') {
        obj.style.color='#376C17';
    }
    else {
        obj.style.color='red';
    } 
    setTimeout("blink(document.getElementById('beware'));", 500);
}

// привью букетов

var hideTimeOut=0;

function show_preview (obj, img_src, lang, item_id, cat_id, toleft) {

    if (!img_src) return false;

    if (hideTimeOut) {
        clearTimeout(hideTimeOut);
    }
    $("#preview").hide();
    
    //document.getElementById('preview_img').src=img_src;
    $("#preview_img").attr('src', img_src);
    $('#preview_img').click(function() {
        document.location.href='/'+lang+'/'+cat_id+'/'+item_id;
    });
    
    $('#fast_order_button').click(function() {
        document.location.href='/'+lang+'/checkout/fast/item/'+item_id;
    });
    
    $("#preview_img").load(function(){
        
        if (toleft) {
            $("#preview").css("top", $(obj).offset().top);
            $("#preview").css("left", $(obj).offset().left - $("#preview_img").width() - 10);
        }
        else {
            $("#preview").css("top", $(obj).offset().top);
            $("#preview").css("left", $(obj).offset().left + $(obj).width());
        }
        $("#preview").fadeIn();
        
    });
    
}

function hide_preview () {
    hideTimeOut=setTimeout('$("#preview").hide()', 300);
}

// показваем видео

function showVideo() {

    // Dialog            
    $('#video').dialog({
        autoOpen: false,
        width: 665,
        buttons: {
            "Закрыть": function() { 
                $(this).dialog("close"); 
            }
        }
    });
    
    
    $('#video').dialog("open");
}


// быстрый заказ

function fastOrder (item_id, lang) {
    
    hide_preview ();
    
    if (lang=='ru') {
        $('#fast_order').dialog({
            autoOpen: false,
            width: 350,
            buttons: {
                "Закрыть": function() { 
                    $(this).dialog("close");
                },
                "Оформить быстрый заказ": function() { 
                    makeFastOrder(item_id, lang);
                }
            }
        });
    }
    else if (lang=='ua') {
        $('#fast_order').dialog({
            autoOpen: false,
            width: 350,
            buttons: {
                "Закрити": function() { 
                    $(this).dialog("close");
                },
                "Оформити швидке замовдення": function() { 
                    makeFastOrder(item_id, lang);
                }
            }
        });
    }
    else if (lang=='en') {
        $('#fast_order').dialog({
            autoOpen: false,
            width: 350,
            buttons: {
                "Close": function() { 
                    $(this).dialog("close");
                },
                "Proceed fast order": function() { 
                    makeFastOrder(item_id, lang);
                }
            }
        });
    }
    
    $('#fast_order').dialog("open");
    
}

function makeFastOrder (item_id, lang) {
    
    var bValid = true;
    var allFields = $([]).add($("#fo_fio")).add($("#fo_phone")).add($("#fo_region")).add($("#fo_city")).add($("#fo_email"));
    var tips = $(".validateTips");
    
    allFields.removeClass('ui-state-error');
    
    function updateTips(t) {
        tips
            .text(t)
            .addClass('ui-state-highlight');
        setTimeout(function() {
            tips.removeClass('ui-state-highlight', 1500);
        }, 500);
    }
    
    function checkLength(o,n,min,max) {

        if ( o.val().length > max || o.val().length < min ) {
            o.addClass('ui-state-error');
            if (lang=='ru') updateTips("Это поле должно содержать от "+min+" до "+max+" знаков.");
            else if ($lang=='ua') updateTips("Це поле повинно бути від "+min+" до "+max+" знаків.");
            else if ($lang=='en') updateTips("Length must be between "+min+" and "+max+".");
             return false;
        } else {
            return true;
        }

    }
    
    function checkRegexp(o,regexp,n) {

        if ( !( regexp.test( o.val() ) ) ) {
            o.addClass('ui-state-error');
            updateTips(n);
            return false;
        } else {
            return true;
        }

    }
    
    bValid = bValid && checkLength($("#fo_fio"),"fo_fio",3,16);
    bValid = bValid && checkLength($("#fo_city"),"fo_city",2,80);
    bValid = bValid && checkLength($("#fo_phone"),"fo_phone",6,80);
    bValid = bValid && checkLength($("#fo_email"),"fo_email",2,80);
    
    bValid = bValid && checkRegexp($("#fo_email"),/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i,"Введите правильный E-mail");
    
    
    if (bValid) {
    
        JsHttpRequest.query(
            '/ajax.php', // backend
            {
                'func' : 'fast_order',
                'item_id' : item_id,
                'fio' : $("#fo_fio").val(),
                'region' : $("#fo_region").val(),
                'city' : $("#fo_city").val(),
                'phone' : $("#fo_phone").val(),
                'email' : $("#fo_email").val(),
                'lang' : lang
            },
            // Function is called when an answer arrives. 
            function(result, cont) {
                // Write the answer.
                
                if (result) {
                    if (result['error']) {
                        tips.text(result['error']);
                    }
                    else {
                        $("#fast_order").html(cont);
                    }
                }
                else {
                    $("#fast_order").html(cont);
                }
                
            },
            false  // do not disable caching
        );
    }
    
}

// выбор региона доставки

var global_region_id=0;
var global_country_id=0;
var current_template = 'region_block2';
var select_city_id = '';

function show_region_select (what, obj, lang) {
    if ($("#" + current_template)) {
        $("#" + current_template).css("top", $(obj).offset().top - 3);
        if (current_template == 'region_block2') {
        	//$("#" + current_template).css("left", $(obj).offset().left - parseInt($('#region_block2').css('width')) + 55);
        	//alert(parseInt($('#region_block2').css('width')));
        }
        else $("#" + current_template).css("left", $(obj).offset().left - 11);
        
        $("#" + current_template + "_header").html($(obj).html() + ' <img src="/images/close.png" width="10" height="10" />');
        $("#" + current_template + "_text").html('<br /><br /><center><img src="/images/ajax-loader.gif" width="32" height="32" align="center" /></center><br /><br />');
        $("#" + current_template).fadeIn();
        
        if (what=='region') {

		$('#' + current_template + '_text').css('width', '150px');

            JsHttpRequest.query(
                '/ajax.php', // backend
                {
                    'func' : 'get_regions',
                    'lang' : language
                },
                // Function is called when an answer arrives. 
                function(result, cont) {
                    // Write the answer.
                    
                    if (result) {
                        if (result['error']) {
                            alert(result['error']);
                        }
                        else {
                            var regions=result['regions'];
                            var html_cont='';
                            
                            for (var i=0; i<regions.length; i++) {
                                html_cont=html_cont+'<a href="javascript:void(0);" onclick="choose_region('+regions[i][0]+', \''+regions[i][1]+'\', \''+lang+'\', \''+regions[i][2]+'\', \''+regions[i][3]+'\')">'+regions[i][1]+'</a><br />';
                            }
                            
                            $("#" + current_template + "_text").html(html_cont);
                            
                        }
                    }
                    else {
                        $("#" + current_template + "_text").html(cont);
                    }
                    
                },
                false  // do not disable caching
            );
        }
        
        if (what=='country') {

		$('#' + current_template + '_text').css('width', '400px');

            JsHttpRequest.query(
                '/ajax.php', // backend
                {
                    'func' : 'get_countries',
                    'region_id' : global_region_id,
                    'lang' : language
                },
                // Function is called when an answer arrives. 
                function(result, cont) {
                    // Write the answer.
                    
                    if (result) {
                        if (result['error']) {
                            alert(result['error']);
                        }
                        else {
                            var countries1 = result['countries1'];
                            var countries2 = result['countries2'];
                            var countries3 = result['countries3'];
                            var html_cont='';
                            
                            
                            
                            for (var i=0; i<countries1.length; i++) {
                                html_cont=html_cont+'<div style="float: left; width: 33%;"><a href="javascript:void(0);" onclick="choose_country('+countries1[i][0]+', \''+countries1[i][1]+'\', \''+lang+'\')">'+countries1[i][1]+'</a></div>';
                                
                                if (countries2[i] !== undefined) {
                                	html_cont=html_cont+'<div style="float: left; width: 33%;"><a href="javascript:void(0);" onclick="choose_country('+countries2[i][0]+', \''+countries2[i][1]+'\', \''+lang+'\')">'+countries2[i][1]+'</a></div>';
                                }
                                
                                if (countries3[i] !== undefined) {
                                	html_cont=html_cont+'<div style="float: left; width: 33%;"><a href="javascript:void(0);" onclick="choose_country('+countries3[i][0]+', \''+countries3[i][1]+'\', \''+lang+'\')">'+countries3[i][1]+'</a></div>';
                                }
                            }
                            
                            $("#" + current_template + "_text").html(html_cont+'<div style="clear: both;"></div>');
                            
                        }
                    }
                    else {
                        $("#" + current_template + "_text").html(cont);
                    }
                    
                },
                false  // do not disable caching
            );
        }
        
        if (what=='city') {

		$('#' + current_template + '_text').css('width', '500px');

            JsHttpRequest.query(
                '/ajax.php', // backend
                {
                    'func' : 'get_cities_for_region',
                    'country_id' : global_country_id,
                    'lang' : language
                },
                // Function is called when an answer arrives. 
                function(result, cont) {
                    // Write the answer.
                    
                    if (result) {
                        if (result['error']) {
                            alert(result['error']);
                        }
                        else {
                        	
                        	var cities1 = [];
                        	var cities2 = [];
                        	var cities3 = [];
                        	var cities4 = [];
                        	
                            //var cities=result['cities'];
                            var cities1 = result['cities1'];
                            if (result['cities2'] !== null) var cities2 = result['cities2'];
                            if (result['cities3'] !== null) var cities3 = result['cities3'];
                            if (result['cities4'] !== null) var cities4 = result['cities4'];

                            var html_cont='';
                            if(site_name == "flora2000.ru" || site_name == "ru-flowers.com")
                            {
                              sUFL_s = "/";
                              sUFL_e = "";
                            }
                            else
                            {
                              sUFL_s = "/"+language+"/cveti-";
                              sUFL_e = "/back";
                            }
                            
                            for (var i=0; i<cities1.length; i++) {
                                if (cities1[i][4]==1) {
                                    // область
                                    html_cont=html_cont+'<div style="float: left; width: 25%; clear: both;"><a href="javascript:void(0);" onclick="get_cities_for_region('+cities1[i][0]+', \''+cities1[i][1]+'\', \''+lang+'\')">'+cities1[i][1]+'</a></div>';
                                    
                                }
                                else {
                                    // простой город
                                    if (cities1[i][3]!='other') html_cont=html_cont+'<div style="float: left; width: 25%; clear: both;"><a href="'+sUFL_s+''+cities1[i][3]+sUFL_e+'">'+cities1[i][1]+'</a></div>';
                                    else html_cont=html_cont+'<div style="float: left; width: 25%; clear: both;"><a href="'+sUFL_s+cities1[i][3]+'-'+cities1[i][2]+sUFL_e+'">'+cities1[i][1]+'</a></div>';
                                }
                                
                                
                                if (cities2[i] !== undefined) {
                                    if (cities2[i][4]==1) {
                                        // область
                                        html_cont=html_cont+'<div style="float: left; width: 25%;"><a href="javascript:void(0);" onclick="get_cities_for_region('+cities2[i][0]+', \''+cities2[i][1]+'\', \''+lang+'\')">'+cities2[i][1]+'</a></div>';
                                        
                                    }
                                    else {
                                        // простой город
                                        if (cities2[i][3]!='other') html_cont=html_cont+'<div style="float: left; width: 25%;"><a href="'+sUFL_s+cities2[i][3]+sUFL_e+'">'+cities2[i][1]+'</a></div>';
                                        else html_cont=html_cont+'<div style="float: left; width: 25%;"><a href="'+sUFL_s+cities2[i][3]+'-'+cities2[i][2]+sUFL_e+'">'+cities2[i][1]+'</a></div>';
                                    }
                                }
                                
                                
                                if (cities3[i] !== undefined) {
                                    if (cities3[i][4]==1) {
                                        // область
                                        html_cont=html_cont+'<div style="float: left; width: 25%;"><a href="javascript:void(0);" onclick="get_cities_for_region('+cities3[i][0]+', \''+cities3[i][1]+'\', \''+lang+'\')">'+cities3[i][1]+'</a></div>';
                                        
                                    }
                                    else {
                                        // простой город
                                        if (cities3[i][3]!='other') html_cont=html_cont+'<div style="float: left; width: 25%;"><a href="'+sUFL_s+cities3[i][3]+sUFL_e+'">'+cities3[i][1]+'</a></div>';
                                        else html_cont=html_cont+'<div style="float: left; width: 25%;"><a href="'+sUFL_s+cities3[i][3]+'-'+cities3[i][2]+sUFL_e+'">'+cities3[i][1]+'</a></div>';
                                    }
                                }
                                
                                
                                if (cities4 !== undefined && cities4[i] !== undefined) {
                                    if (cities4[i][4]==1) {
                                        // область
                                        html_cont=html_cont+'<div style="float: left; width: 25%;"><a href="javascript:void(0);" onclick="get_cities_for_region('+cities4[i][0]+', \''+cities4[i][1]+'\', \''+lang+'\')">'+cities4[i][1]+'</a></div>';
                                        
                                    }
                                    else {
                                        // простой город
                                        if (cities4[i][3]!='other') html_cont=html_cont+'<div style="float: left; width: 25%;"><a href="'+sUFL_s+cities4[i][3]+sUFL_e+'">'+cities4[i][1]+'</a></div>';
                                        else html_cont=html_cont+'<div style="float: left; width: 25%;"><a href="'+sUFL_s+cities4[i][3]+'-'+cities4[i][2]+sUFL_e+'">'+cities4[i][1]+'</a></div>';
                                    }
                                }
                            }
                            
                            html_cont=html_cont+'<div style="clear: both;"></div>'+cont
                            
                            if (global_country_id==5) {
                                if (lang=='ru') html_cont=html_cont+'<br /><br /><a href="/'+lang+'/regions/ukraine/ukraine"><b>Все города Украины</b></a>';
                                if (lang=='ua') html_cont=html_cont+'<br /><br /><a href="/'+lang+'/regions/ukraine/ukraine"><b>Усі міста України</b></a>';
                                if (lang=='en') html_cont=html_cont+'<br /><br /><a href="/'+lang+'/regions/ukraine/ukraine"><b>All cities of Ukraine</b></a>';
                            }
                            
                            $("#" + current_template + "_text").html(html_cont);
                            
                        }
                    }
                    else {
                        $("#" + current_template + "_text").html(cont);
                    }
                    
                },
                false  // do not disable caching
            );

	

        }

    if (select_city_id) var d = $('#' + select_city_id).css('width');
    else var d = $('#city_choose').css('width');

	if (current_template == 'region_block2') $("#" + current_template).css("left", $(obj).offset().left - parseInt($('#' + current_template).css('width')) + parseInt(d) + 20);
        
    }
    
}

function show_region_select_right (what, obj, lang) {
    if ($("#region_block_right")) {
        $("#region_block_right").css("top", $(obj).offset().top - 3);
        $("#region_block_right").css("left", $(obj).offset().left - 11);
        
        $("#rb_header_right_text").html($(obj).html());
        $("#region_block_right_text").html('<br /><br /><center><img src="/images/ajax-loader.gif" width="32" height="32" align="center" /></center><br /><br />');
        $("#region_block_right").fadeIn();
        
        if (what=='region') {
            JsHttpRequest.query(
                '/ajax.php', // backend
                {
                    'func' : 'get_regions',
                    'lang' : lang
                },
                // Function is called when an answer arrives. 
                function(result, cont) {
                    // Write the answer.
                    
                    if (result) {
                        if (result['error']) {
                            alert(result['error']);
                        }
                        else {
                            var regions=result['regions'];
                            var html_cont='';
                            
                            $('#region_block_right_text').css('width', '150px');
                            
                            for (var i=0; i<regions.length; i++) {
                                html_cont=html_cont+'<a href="javascript:void(0);" onclick="choose_region('+regions[i][0]+', \''+regions[i][1]+'\', \''+lang+'\', \''+regions[i][2]+'\', \''+regions[i][3]+'\')">'+regions[i][1]+'</a><br />';
                            }
                            
                            $("#region_block_right_text").html(html_cont);
                            
                        }
                    }
                    else {
                        $("#region_block_right_text").html(cont);
                    }
                    
                },
                false  // do not disable caching
            );
        }
        
        if (what=='country') {
            JsHttpRequest.query(
                '/ajax.php', // backend
                {
                    'func' : 'get_countries',
                    'region_id' : global_region_id,
                    'lang' : lang
                },
                // Function is called when an answer arrives. 
                function(result, cont) {
                    // Write the answer.
                    
                    if (result) {
                        if (result['error']) {
                            alert(result['error']);
                        }
                        else {
                            var countries1 = result['countries1'];
                            var countries2 = result['countries2'];
                            var countries3 = result['countries3'];
                            var html_cont='';
                            
                            $('#region_block_right_text').css('width', '400px');
                            
                            for (var i=0; i<countries1.length; i++) {
                                html_cont=html_cont+'<div style="float: left; width: 33%;"><a href="javascript:void(0);" onclick="choose_country('+countries1[i][0]+', \''+countries1[i][1]+'\', \''+lang+'\')">'+countries1[i][1]+'</a></div>';
                                
                                if (countries2[i] !== undefined) {
                                	html_cont=html_cont+'<div style="float: left; width: 33%;"><a href="javascript:void(0);" onclick="choose_country('+countries2[i][0]+', \''+countries2[i][1]+'\', \''+lang+'\')">'+countries2[i][1]+'</a></div>';
                                }
                                
                                if (countries3[i] !== undefined) {
                                	html_cont=html_cont+'<div style="float: left; width: 33%;"><a href="javascript:void(0);" onclick="choose_country('+countries3[i][0]+', \''+countries3[i][1]+'\', \''+lang+'\')">'+countries3[i][1]+'</a></div>';
                                }
                            }
                            
                            $("#region_block_right_text").html(html_cont+'<div style="clear: both;"></div>');
                            
                        }
                    }
                    else {
                        $("#region_block_right_text").html(cont);
                    }
                    
                },
                false  // do not disable caching
            );
        }
        
        if (what=='city') {
            JsHttpRequest.query(
                '/ajax.php', // backend
                {
                    'func' : 'get_cities_for_region',
                    'country_id' : global_country_id,
                    'lang' : lang
                },
                // Function is called when an answer arrives. 
                function(result, cont) {
                    // Write the answer.
                    
                    if (result) {
                        if (result['error']) {
                            alert(result['error']);
                        }
                        else {
                        	
                        	var cities1 = [];
                        	var cities2 = [];
                        	var cities3 = [];
                        	var cities4 = [];
                        	
                            //var cities=result['cities'];
                            var cities1 = result['cities1'];
                            if (result['cities2'] !== null) var cities2 = result['cities2'];
                            if (result['cities3'] !== null) var cities3 = result['cities3'];
                            if (result['cities4'] !== null) var cities4 = result['cities4'];
                            
                            var html_cont='';
                            
                            $('#region_block_right_text').css('width', '500px');
                            
                            for (var i=0; i<cities1.length; i++) {
                                if (cities1[i][4]==1) {
                                    // область
                                    html_cont=html_cont+'<div style="float: left; width: 25%; clear: both;"><a href="javascript:void(0);" onclick="get_cities_for_region('+cities1[i][0]+', \''+cities1[i][1]+'\', \''+lang+'\')">'+cities1[i][1]+'</a></div>';
                                    
                                }
                                else {
                                    // простой город
                                    if (cities1[i][3]!='other') html_cont=html_cont+'<div style="float: left; width: 25%; clear: both;"><a href="/'+lang+'/cveti-'+cities1[i][3]+'/back">'+cities1[i][1]+'</a></div>';
                                    else html_cont=html_cont+'<div style="float: left; width: 25%; clear: both;"><a href="/'+lang+'/cveti-'+cities1[i][3]+'-'+cities1[i][2]+'/back">'+cities1[i][1]+'</a></div>';
                                }
                                
                                
                                if (cities2[i] !== undefined) {
                                    if (cities2[i][4]==1) {
                                        // область
                                        html_cont=html_cont+'<div style="float: left; width: 25%;"><a href="javascript:void(0);" onclick="get_cities_for_region('+cities2[i][0]+', \''+cities2[i][1]+'\', \''+lang+'\')">'+cities2[i][1]+'</a></div>';
                                        
                                    }
                                    else {
                                        // простой город
                                        if (cities2[i][3]!='other') html_cont=html_cont+'<div style="float: left; width: 25%;"><a href="/'+lang+'/cveti-'+cities2[i][3]+'/back">'+cities2[i][1]+'</a></div>';
                                        else html_cont=html_cont+'<div style="float: left; width: 25%;"><a href="/'+lang+'/cveti-'+cities2[i][3]+'-'+cities2[i][2]+'/back">'+cities2[i][1]+'</a></div>';
                                    }
                                }
                                
                                
                                if (cities3[i] !== undefined) {
                                    if (cities3[i][4]==1) {
                                        // область
                                        html_cont=html_cont+'<div style="float: left; width: 25%;"><a href="javascript:void(0);" onclick="get_cities_for_region('+cities3[i][0]+', \''+cities3[i][1]+'\', \''+lang+'\')">'+cities3[i][1]+'</a></div>';
                                        
                                    }
                                    else {
                                        // простой город
                                        if (cities3[i][3]!='other') html_cont=html_cont+'<div style="float: left; width: 25%;"><a href="/'+lang+'/cveti-'+cities3[i][3]+'/back">'+cities3[i][1]+'</a></div>';
                                        else html_cont=html_cont+'<div style="float: left; width: 25%;"><a href="/'+lang+'/cveti-'+cities3[i][3]+'-'+cities3[i][2]+'/back">'+cities3[i][1]+'</a></div>';
                                    }
                                }
                                
                                
                                if (cities4 !== undefined && cities4[i] !== undefined) {
                                    if (cities4[i][4]==1) {
                                        // область
                                        html_cont=html_cont+'<div style="float: left; width: 25%;"><a href="javascript:void(0);" onclick="get_cities_for_region('+cities4[i][0]+', \''+cities4[i][1]+'\', \''+lang+'\')">'+cities4[i][1]+'</a></div>';
                                        
                                    }
                                    else {
                                        // простой город
                                        if (cities4[i][3]!='other') html_cont=html_cont+'<div style="float: left; width: 25%;"><a href="/'+lang+'/cveti-'+cities4[i][3]+'/back">'+cities4[i][1]+'</a></div>';
                                        else html_cont=html_cont+'<div style="float: left; width: 25%;"><a href="/'+lang+'/cveti-'+cities4[i][3]+'-'+cities4[i][2]+'/back">'+cities4[i][1]+'</a></div>';
                                    }
                                }
                            }
                            
                            html_cont=html_cont+'<div style="clear: both;"></div>'+cont
                            
                            if (global_country_id==5) {
                                if (lang=='ru') html_cont=html_cont+'<br /><br /><a href="/'+lang+'/regions/ukraine/ukraine"><b>Все города Украины</b></a>';
                                if (lang=='ua') html_cont=html_cont+'<br /><br /><a href="/'+lang+'/regions/ukraine/ukraine"><b>Усі міста України</b></a>';
                                if (lang=='en') html_cont=html_cont+'<br /><br /><a href="/'+lang+'/regions/ukraine/ukraine"><b>All cities of Ukraine</b></a>';
                            }
                            
                            $("#region_block_right_text").html(html_cont);
                            
                        }
                    }
                    else {
                        $("#region_block_right_text").html(cont);
                    }
                    
                },
                false  // do not disable caching
            );
        }
        
    }
    
}


function choose_region (id, name, lang, autochoose_country, country_name) {
    
    global_region_id=id;

    //$('#city_choose').css('display', 'none');
    if ( autochoose_country > 0 ) {
        //$("#region_choose").html('<b>'+name+'</b> <img src="/images/green_arrow.gif" />');
        //$("#country_choose").html('<b>'+country_name+'</b> <img src="/images/green_arrow.gif" />');
        
        $('#region_block2').css('display', 'none');
        //$("#country_choose").fadeIn();
        
        global_country_id = autochoose_country;
        
        //if (lang=='ru') $("#city_choose").html('<b>Выберите город</b> <img src="/images/green_arrow.gif" />');
        //else if (lang=='ua') $("#city_choose").html('<b>Виберіть місто</b> <img src="/images/green_arrow.gif" />');
        //else $("#city_choose").html('<b>Choose city</b> <img src="/images/green_arrow.gif" />');
        
        //$("#city_choose").fadeIn();
        //$('#city_choose').css('display', 'inline');
        
        if (select_city_id) 
					show_region_select('city', $("#" + select_city_id), lang);
        else if((arguments[5] != "") && (arguments[5] != undefined))
        	show_region_select('city', $("#"+arguments[5]), lang);
        else 
					show_region_select('city', $("#city_choose"), lang);
        
    }
    else {
        //$("#region_choose").html('<b>'+name+'</b> <img src="/images/green_arrow.gif" />');
        //if (lang=='ru') $("#country_choose").html('<b>Выберите страну</b> <img src="/images/green_arrow.gif" />');
        //if (lang=='ua') $("#country_choose").html('<b>Виберіть країну</b> <img src="/images/green_arrow.gif" />');
        //if (lang=='en') $("#country_choose").html('<b>Select country</b> <img src="/images/green_arrow.gif" />');
        
        $('#region_block2').css('display', 'none');
        //$("#country_choose").fadeIn();
        
        if (select_city_id) show_region_select('country', $("#" + select_city_id), lang);
        else show_region_select('country', $("#city_choose"), lang);
    }
}

function choose_country (id, name, lang) {
    
    global_country_id=id;
    
    //$("#country_choose").html('<b>'+name+'</b> <img src="/images/green_arrow.gif" />');
    //if (lang=='ru') $("#city_choose").html('<b>Выберите город</b> <img src="/images/green_arrow.gif" />');
    //if (lang=='ua') $("#city_choose").html('<b>Виберіть місто</b> <img src="/images/green_arrow.gif" />');
    //if (lang=='en') $("#city_choose").html('<b>Select city</b> <img src="/images/green_arrow.gif" />');
    
    $('#region_block2').css('display', 'none');
    //$("#city_choose").fadeIn();
    //$('#city_choose').css('display', 'inline');
    
    show_region_select('city', $("#city_choose"), lang);
}

function get_cities_for_region (id, name, lang) {
    if (lang=='ru') var html_cont='<b>'+name+'</b> <a href="javascript:void(0);" onclick="show_region_select(\'city\', $(\'#city_choose\'), \''+lang+'\')">Назад к областям</a><br /><br />';
    if (lang=='ua') var html_cont='<b>'+name+'</b> <a href="javascript:void(0);" onclick="show_region_select(\'city\', $(\'#city_choose\'), \''+lang+'\')">Назад до районів</a><br /><br />';
    if (lang=='en') var html_cont='<b>'+name+'</b> <a href="javascript:void(0);" onclick="show_region_select(\'city\', $(\'#city_choose\'), \''+lang+'\')">Back to regions</a><br /><br />';
    
    JsHttpRequest.query(
        '/ajax.php', // backend
        {
            'func' : 'get_cities_for_region',
            'country_id' : global_country_id,
            'region_id' : id,
            'lang' : lang
        },
        // Function is called when an answer arrives. 
        function(result, cont) {
            // Write the answer.
            
            if (result) {
                if (result['error']) {
                    alert(result['error']);
                }
                else {
                	
                    var cities1 = result['cities1'];
                    var cities2 = result['cities2'];
                    var cities3 = result['cities3'];
                    var cities4 = result['cities4'];
                    
                    $("#"+current_template+"_text").css('width', '500px');
                    
                    for (var i=0; i<cities1.length; i++) {
                        // html_cont=html_cont+'<div style="float: left; width: 25%;"><a href="/'+lang+'/cveti-'+cities[i][3]+'">'+cities[i][1]+'</a></div>';
                        if (cities1[i][3]!='other') html_cont=html_cont+'<div style="float: left; width: 25%; clear: both;"><a href="/'+lang+'/cveti-'+cities1[i][3]+'/back">'+cities1[i][1]+'</a></div>';
                        else html_cont=html_cont+'<div style="float: left; width: 25%; clear: both;"><a href="/'+lang+'/cveti-'+cities1[i][3]+'-'+cities1[i][2]+'/back">'+cities1[i][1]+'</a></div>';
                        
                        if (cities2 !== null)
                        if (cities2[i] !== undefined) {
                        	if (cities2[i][3]!='other') html_cont=html_cont+'<div style="float: left; width: 25%;"><a href="/'+lang+'/cveti-'+cities2[i][3]+'/back">'+cities2[i][1]+'</a></div>';
                        	else html_cont=html_cont+'<div style="float: left; width: 25%;"><a href="/'+lang+'/cveti-'+cities2[i][3]+'-'+cities2[i][2]+'/back">'+cities2[i][1]+'</a></div>';
                        }
                        
                        if (cities3 !== null)
                        if (cities3[i] !== undefined) {
                        	if (cities3[i][3]!='other') html_cont=html_cont+'<div style="float: left; width: 25%;"><a href="/'+lang+'/cveti-'+cities3[i][3]+'/back">'+cities3[i][1]+'</a></div>';
                        	else html_cont=html_cont+'<div style="float: left; width: 25%;"><a href="/'+lang+'/cveti-'+cities3[i][3]+'-'+cities3[i][2]+'/back">'+cities3[i][1]+'</a></div>';
                        }
                        
                        if (cities4 !== null)
                        if (cities4[i] !== undefined) {
                        	if (cities4[i][3]!='other') html_cont=html_cont+'<div style="float: left; width: 25%;"><a href="/'+lang+'/cveti-'+cities4[i][3]+'/back">'+cities4[i][1]+'</a></div>';
                        	else html_cont=html_cont+'<div style="float: left; width: 25%;"><a href="/'+lang+'/cveti-'+cities4[i][3]+'-'+cities4[i][2]+'/back">'+cities4[i][1]+'</a></div>';
                        }
                    }
                    
                    $("#"+current_template+"_text").html(html_cont+'<div style="clear: both;"></div>'+cont);
                    
                }
            }
            else {
                $("#"+current_template+"_text").html(cont);
            }
            
            $("#"+current_template).fadeIn();
        },
        false  // do not disable caching
    );
}

// функция смены региона доставки на странице товара

function prodChangeRegion (prod_id) {
    
    JsHttpRequest.query(
        '/ajax.php', // backend
        {
            'func' : 'get_price4region',
            'prod_id' : prod_id,
            'region' : $("#region").val(),
            'lang' : lang
        },
        // Function is called when an answer arrives. 
        function(result, cont) {
            // Write the answer.
            
            if (result) {
                if (result['error']) {
                    alert(result['error']);
                }
                else {
                    
                    if (result['price']==0) {
                        if (lang=='ru') alert('Вы не можете заказать этот товар для выбранного региона, пожалуйста, выберите другой товар');
                        if (lang=='ua') alert('Ви не  можете замовити цей товар  для вибраного регіону, будь  ласка, виберіть інший товар');
                        if (lang=='en') alert('You can`t order this product for this region');
                    }
                    
                    $( "#price_place_" + result['prod_id'] ).html( result['price'] );
                    
                    $( "#price_premium_place_" + result['prod_id'] ).html( result['price_premium'] );
                    
                    $( "#price_period_place_" + result['prod_id'] ).html( result['price_period'] );
                    
                    $( "#price_period_premium_place_" + result['prod_id'] ).html( result['price_period_premium'] );
                    
                    $('#region_block_text').css('width', '500px');
                    if (cont) alert(cont);
                }
            }
            else {
                alert(cont);
            }
        },
        false  // do not disable caching
    );
}


/**
* 
* Функция ajax смены цены
* 
*/

var curr_val = '', premium_rate = 0, prices_arr = {};

function ajaxPriceUpdate ( currency, currText ) {

    var qdata = '';
    
    //собираем все элементы с ценами
    
    $('span[id*="price_place_"]').each(function(){
        var elemId = this.id;
        elemId = elemId.substring( 12 );
        
        qdata += '&prod[]=' + elemId;
    });
    
    if (!qdata) return false;
    
    $.ajax({
        type: "GET",
        url: '/ajax.php',
        data: "currency="+ currency + qdata +"&func=get_product_prices&lang=" + lang,
        success: function(res_data) {
            
            var prices = $.parseJSON( res_data );
            
            curr_val = currency;
            
            if ( prices ) {
                for(var i=0; i<prices.length; i++) 
								{
                    
                    /*$( 'span[id="price_name_place_'+ prices[i]['id'] +'"]' ).each( function () { 
                        $(this).html(currText);
                    });*/
                    	$( "#price_name_place_" + prices[i]['id'] ).html( currText );
                    
	                    $( "#price_place_" + prices[i]['id'] ).html( prices[i]['price'] );
	                    
	                    $( "#price_premium_place_" + prices[i]['id'] ).html( Math.round(prices[i]['price'] * premium_rate) );
	                    
	                    $( "#price_period_place_" + prices[i]['id'] ).html( prices[i]['price_period'] );
	                    
	                    $( "#price_period_premium_place_" + prices[i]['id'] ).html( Math.round(prices[i]['price_period'] * premium_rate) );
	                    
	                    
											if($("#popup_window_second").css("display") == "block")
	                    {
	                    	if($("#popup_window_second #price_place_" + prices[i]['id']).html()!="")
	                    	{
		                    	$( "#popup_window_second #price_name_place_" + prices[i]['id'] ).html( currText );
	                    
			                    $( "#popup_window_second #price_place_" + prices[i]['id'] ).html( prices[i]['price'] );
			                    
			                    $( "#popup_window_second #price_premium_place_" + prices[i]['id'] ).html( Math.round(prices[i]['price'] * premium_rate) );
			                    
			                    $( "#popup_window_second #price_period_place_" + prices[i]['id'] ).html( prices[i]['price_period'] );
			                    
			                    $( "#popup_window_second #price_period_premium_place_" + prices[i]['id'] ).html( Math.round(prices[i]['price_period'] * premium_rate) );
		                    }
	                    }
                }
                
                $('select[name="price_select"]').each(function (){
                    $(this).val(curr_val);
                });
                
                $("#currency_block").hide('blind');
            }
            
        }
    });
    
    return true;
    
}

function indexPriceChange ( currency ) {
    ajaxPriceUpdate(currency);

}


/**
 * Функция показа оплат на стр букета
 */

var paymentWindow = false;

function showPayments(pId) {
	
    $.ajax({
        type: "GET",
        url: '/ajax.php',
        data: "func=get_payment&lang_r=" + lang_r + "&id=" + pId,
        success: function(res_data) {
            
            if ( res_data ) {
            	//var payment = $.parseJSON( res_data );
            	
            	if ( !paymentWindow ) {
            		paymentWindow = document.createElement('div');
            		paymentWindow.setAttribute( 'id', 'payment_window' );
            		paymentWindow.setAttribute( 'title', '' );
            		paymentWindow.setAttribute( 'style', 'display: none;' );
            		document.body.appendChild(paymentWindow);
            	}
            	
            	var endPos = res_data.indexOf( '{te}' );
            	var title = res_data.substr(0, endPos);
            	var text = res_data.substr(endPos + 4);
            	
            	$( paymentWindow ).attr( 'title', title );
            	$( '#ui-dialog-title-payment_window' ).html( title );
            	$( paymentWindow ).html( text );
            	$( paymentWindow ).show();
            	$( "#payment_window" ).dialog();
            	//setTimeout("$( '#payment_window' ).parent().css('left', '50%');", 0);
            	
            	var p = $("#payments_block");
            	var offset = p.offset();
            	//alert("left: " + offset.left + ", top: " + offset.top);
            	
            	$( '#payment_window' ).parent().css('left', offset.left + 3 + 'px');
            	$( '#payment_window' ).parent().css('top', offset.top - document.height + 220 + 'px');

            	
            }
            
        }
    });
	
}

/**
 * Функция показа контента в сплывающем окне
 */

var contentWindow = false;

function showContent( contId ) {
	
    $.ajax({
        type: "GET",
        url: '/ajax.php',
        data: "func=get_content&lang_r=" + lang_r + "&cont_id=" + contId,
        success: function(res_data) {
            
            if ( res_data ) {
            	
            	if ( !contentWindow ) {
            		contentWindow = document.createElement('div');
            		contentWindow.setAttribute( 'id', 'content_window' );
            		contentWindow.setAttribute( 'title', '' );
            		contentWindow.setAttribute( 'style', 'display: none;' );
            		document.body.appendChild(contentWindow);
            	}
            	
            	var endPos = res_data.indexOf( '{te}' );
            	var title = res_data.substr(0, endPos);
            	var text = res_data.substr(endPos + 4);
            	
            	//var data = $.parseJSON( res_data );
            	
            	$( contentWindow ).attr( 'title', title );
       	
            	$( contentWindow ).html( text );
            	//$( contentWindow ).show();
            	$( "#content_window" ).dialog({ width: 800, height: 600 });
            	
            }
            
        }
    });
	
}

/**
 * Логирование кликов по онлайн чату
 * @returns true
 */

function chatClicked() {
    $.ajax({
        type: "GET",
        url: '/ajax.php',
        data: "func=chat_clicked&lang=" + lang,
        success: function(res_data) {
            
            return true;
            
        }
    });
}

/**
 * Переключение картинок
 */

var sloganId = -1;

function switchImages () {
	
	if (typeof( headerImages ) == 'undefined' || !$('#slogan')) return false; // Массив с картинками
	
	sloganId ++;
	
	if (typeof( headerImages[sloganId] ) == 'undefined') sloganId = 0;
	//alert(typeof( headerImages[sloganId] ));
	$('#slogan').css( 'background-image', 'url("' + headerImages[sloganId]['img'] + '")' );
	$('#slogan').html( headerImages[sloganId]['title'] );
	$('#slogan').click( function(){document.location.href = headerImages[sloganId]['href']} );
	
	setTimeout('switchImages ()', 5000);
	
}

$().ready(function(){switchImages();});



/*

ya_maps.js

*/




// Автозаполнение адреса призаказе


var map, geoResult;

// Создание обработчика для события window.onLoad

if (typeof( YMaps ) != 'undefined') {
	YMaps.jQuery(function () {
		// Создание экземпляра карты и его привязка к созданному контейнеру
		map = new YMaps.Map(YMaps.jQuery("#YMapsID")[0]);

		// Установка для карты ее центра и масштаба
		map.setCenter(new YMaps.GeoPoint(37.64, 55.76), 10);

		// Добавление элементов управления
		map.addControl(new YMaps.TypeControl());
	});
}


function search() {
    
    // var query = 'Киев, Бориса гмыри';
    var query = $('#rec_address').val();
    
    // Запуск процесса геокодирования
    var geocoder = new YMaps.Geocoder(query, {results: 1, boundedBy: map.getBounds()});
    
    // Создание обработчика для успешного завершения геокодирования
    YMaps.Events.observe(geocoder, geocoder.Events.Load, function () {
        // Если объект был найден, то добавляем его на карту
        // и центрируем карту по области обзора найденного объекта
        
        if (this.length()) {
            geoResult = this.get(0);
            //alert(geoResult.text);
            alert(geoResult.AddressDetails.Country.Locality.DependentLocality.DependentLocalityName);
            
            //map.addOverlay(geoResult);
            //map.setBounds(geoResult.getBounds());
        }else {
            alert("Ничего не найдено")
        }
    });

    // Процесс геокодирования завершен неудачно
    YMaps.Events.observe(geocoder, geocoder.Events.Fault, function (geocoder, error) {
        alert("Произошла ошибка: " + error);
    })

}

function showVariants() {
    // var query = 'Киев, Бориса гмыри';
    
    if ( $('#city').val() != 'kiev' ) {
        return false;
    }
    
    var query = $('#rec_address').val();
    
    var sres = '';
    
    if (query.length<3) return false;
    
    query = 'Киев, '+query;
    
    
    
    // Запуск процесса геокодирования
    var geocoder = new YMaps.Geocoder(query, {results: 5, boundedBy: map.getBounds()});
    
    // Создание обработчика для успешного завершения геокодирования
    YMaps.Events.observe(geocoder, geocoder.Events.Load, function () {
        // Если объект был найден, то добавляем его на карту
        // и центрируем карту по области обзора найденного объекта
        
        if (this.length()) {
            geoResult = this.get(0);
            //alert(geoResult.text);
            //alert(geoResult.text);
            
            var i=0;
            
            while (geoResult = this.get(i)) {
                i++;
                
                var address = geoResult.text;
                
                if (address.indexOf(',')) address = address.substr( address.indexOf(',')+1 );
                if (address.indexOf(',')) address = address.substr( address.indexOf(',')+1 );
                
                sres += '<a onclick="setResult(\'' + address + '\')" sytle="cursor:pointer;" href="javascript:void(0)">' + address + "<br />\n";
            }
            
/*            for (var geoResult in this) {
                sres += geoResult.AddressDetails.Country.Locality.DependentLocality.DependentLocalityName+"\n";
            }*/
            
            var span = document.getElementById('search_span');
            
            if (!span) {
                var span = document.createElement('span'); 
            }
            
            $(span).html('<nobr>' + sres + '</nobr>');
            
            $(span).attr('id', 'search_span');
            $(span).css('position', 'absolute');
            $(span).css('display', 'block');
            $(span).css('width', $('#rec_address').css('width'));
            $(span).css('top', $('#rec_address').css('top'));
            $(span).css('overflow-x', 'hidden');
            $(span).css('background-color', '#FFF');
            $(span).css('border', '1px solid #A7A6AA');
            
                        
            /*$(span).css(
                "position: absolute; "+
                "display: block; "+
                "width: "+$('#address').css('width')+"px; "+
                "top: "+$('#address').css('top')+ +"px; "
            );*/
            
            //alert( sres );
            
            $('#rec_address').after(span);
            
            //$('#res').html(sres);
            //alert (sres);
            
            //map.addOverlay(geoResult);
            //map.setBounds(geoResult.getBounds());
        }else {
            alert("Ничего не найдено")
        }
    });

    // Процесс геокодирования завершен неудачно
    YMaps.Events.observe(geocoder, geocoder.Events.Fault, function (geocoder, error) {
        alert("Произошла ошибка: " + error);
    })
}

function setResult (val) {
    
    //if (val.indexOf(',')) val = val.substr( val.indexOf(',')+1 );

    var region_name = val.substr( 0, val.indexOf(',') );
    
    $("#region").val( region_name );
    
    if (val.indexOf(',')) val = val.substr( val.indexOf(',')+2 );
    
    $("#rec_address").val(val);
    //$("#search_span").css('display', 'none');
    
    $.ajax({
        type: "GET",
        url: '/ajax.php',
        data: "func=get_region_nick&lang=" + lang + "&region_name=" + region_name,
        success: function(res_data) {
            if ( res_data ) {
                $("#city").val( res_data );
            }
            
        }
    });
    
    return true;
}

function hideResults () {
    setTimeout('$("#search_span").hide()', 100);
}


/**
 * Удаляем товар из корзины
 */

function cartDelete (productId) {
	$.ajax ({
        type: "POST",
        url: '/ajax.php',
        data: "func=cart_delete&id=" + productId + '&lang=' + lang,
        success: function(res_data) {
        	
        	$('#products').html(res_data);
        	
        }
	});
}

/**
 * Показываем блок с share link
 */
 
function wannaShowShare(socialPage) {
	
	var link = false;
	
	if (socialPage == 'fb') {
		link = 'http://www.facebook.com/sharer.php?u=' + encodeURIComponent('http://www.ufl.ua/' + wannaLink) + '&t=' + encodeURIComponent(wannaText);
	}
	
	if (socialPage == 'vk') {
		link = 'http://vkontakte.ru/share.php?url=' + encodeURIComponent('http://www.ufl.ua/' + wannaLink) + '&title=' + encodeURIComponent(wannaText);
	}
	
	if (socialPage == 'tw') {
		link = 'https://twitter.com/share?original_referer=' + encodeURIComponent('http://www.ufl.ua/' + wannaLink) + '&source=tweetbutton&text=' + encodeURIComponent(wannaTextTwiter) + '&url=' + encodeURIComponent('http://www.ufl.ua/' + wannaLink) + '&via=UFL.UA';
	}
	
	if (link) {
	
		var win = window.open(link, '_blank', 'width=700,height=500');
	
		/*var layer = document.createElement('iframe');
		
		$(layer).attr('src', link);
		
		$(layer).attr('width', '100%');
		$(layer).attr('height', '100%');
		$(layer).attr('allowtransparency', 'true');
		$(layer).css('border', '0');
		
		
		$('#wanna_gift').html('');
		$('#wanna_gift').append(layer);*/
	}
	
}

/**
 * Показываем блок выбора валюты
 */
 
function showCurrBlock(obj) {
	$("#currency_block").css("top", $(obj).offset().top + parseInt($(obj).css('height')));
	$("#currency_block").css("left", $(obj).offset().left);
	
	$("#currency_block").show('blind');
}

/**
 * Показываем всплывающее окно с корзиной / заказом
 */

function showPopupWin(link) {
	$("#currency_block").hide();
	var shadow = document.createElement('div');
		
	$(shadow).attr('class', 'shadow');
	$(shadow).attr('id', 'shadow');
	//$(shadow).css('top', getScrollTopPos());
	if(navigator.appName == 'Microsoft Internet Explorer')
	{
		$(shadow).insertBefore('body');
		//$("body").append(shadow);
	}
	else
	{
		$("body").append(shadow);
	}
	
	// кнопка закрыть
	
	var close = document.createElement('span');
	
	$(close).attr('class', 'close_button');
	$(close).click(function(){$('#shadow').remove();});
	
	//$(shadow).append(close);
	
	// фрейм
	
	var iframe = document.createElement('iframe');

	$(iframe).attr('src', link);
	$(iframe).attr('id', 'iframe');
	$(iframe).attr('allowtransparency', 'true');
	$(iframe).attr('class', 'layer');
	$(iframe).css('height', $(window).height());
	$(shadow).append(iframe);
	//$(iframe).load(function(){resizePopup()});
}

function resizePopup () {//document.body.children[18].children[1].contentDocument.body.clientHeight
	//alert($(document.getElementById('iframe').contentDocument.body).height());
	
	var height = $(document.getElementById('iframe').contentDocument.body).height() + 40;
	
	var winHeight = $(window).height() - 40;
	
	if (height > winHeight) height = winHeight;
	//alert(height);
	$('#iframe').css('height', height + 'px');
	
	setTimeout(resizePopup(), 500);
}

/*$(document).scroll(function(){
	$('#shadow').css('top', window.pageYOffset);
});*/

/**
* Получает позицию скрола
*/

function getScrollTopPos () {
    if ('pageXOffset' in window) {  // all browsers, except IE before version 9
        var scrollTop = window.pageYOffset;
    }
    else {      // Internet Explorer before version 9
        //var zoomFactor = GetZoomFactor ();
        var scrollTop = document.documentElement.scrollTop;
    }
    
    return scrollTop;
}

function moveCheckoutDiv () {
	$('#shadow').css('top', getScrollTopPos());
}

//window.onscroll = moveCheckoutDiv;

$(document).resize(function(){
	$('#iframe').css('height', $(window).height() - 40);
});

$(document).ready(function(){

  //показываем проактивный чат для пользователей которые зашли на сайт впервый раз
  var isOurUser = checkCookie("proactive_chat");
  if(!isOurUser && !is_ru && !is_ru_flowers_com)
  {
    setTimeout("showProactiveHelp()", 60000);
    setCookie("proactive_chat", "1", 365);
  }
	
  if((is_city_page || is_country_page) && !is_ru && !is_ru_flowers_com)
  {
    /*if(!is_city_page && !is_country_page)
    {
      getAjaxProducts(1, "first_boquets", 0);
      getAjaxProducts(2, "second_boquets", 0);
      var iFirstBlockLoaded = 0;
      var iSecondBlockLoaded = 0;
    }*/
    if(index_page == '1'){
        addAllProductsButton();
    }
    
  }

 $(window).scroll(function(){
		var scroll = $(window).scrollTop();
		/*if(scroll > 1800)
			showToTop();
		else
			hideToTop();*/
      
   if($("#search_form").css("display") == "block")
   {
    iTop = parseInt(scroll)+170;
    iCloseTop = iTop+10;
    sTop = iTop+"px";
    sCloseTop = iCloseTop+"px";
    $("#search_form").css("margin-top", sTop);
    $("#close_search_block").css("margin-top", sCloseTop);
   }
   
    
    /*if(index_page == '1' && !is_ru && !is_ru_flowers_com && !is_city_page && !is_country_page)
    {
      iFirstBlockPosition = document.getElementById("first_boquets").offsetTop;
      iSecondBlockPosition = document.getElementById("second_boquets").offsetTop;
      if((scroll+500) > iFirstBlockPosition && scroll < iSecondBlockPosition && iFirstBlockLoaded == 0)
      {
        getAjaxProducts(1, "first_boquets", 1);
        iFirstBlockLoaded = 1;
      }
      else if((scroll+500) > iSecondBlockPosition && iSecondBlockLoaded == 0)
      {
        getAjaxProducts(2, "second_boquets", 1);
        iSecondBlockLoaded = 1;
      }
    }*/
    
    iWindowHeight = document.body.offsetHeight;
    iShowFloristHeight = iWindowHeight - 2000;
    
		/*if((index_page == '1' || is_city_page || is_country_page) && (scroll > iShowFloristHeight) && $("#footer_search_products").css("display") == "none")
    {
    	showFloriristBlock();
    }
    else if((index_page == '1' || is_city_page || is_country_page) && (iShowFloristHeight > scroll) && $("#footer_search_products").attr("style") != "")
    {
			$("#footer_search_products").css("display", "none");
  		$("#footer_search_products").attr("style", "display: none;");
  		$("#footer_search_products").html("");
  		$("#close_footer_search").css("display", "none");
    }*/
	
  });
  
  /*if(!is_ru && !is_ru_flowers_com)
  	rotateBanners();*/
  	
   $('#icq_block').mouseover(function()
    {
      
       
    });
});

/**
	@function: showTollTip()
	@author: Nazar Kaznadzey
	@date: 2012-01-19
	@params:
		required:
			obj - element for action
			sText - text for showwing
		is arguments:
			2 - what corner
			3 - return block
			4 - border width
			5 - radius for border
			6 - border padding
			7 - text align
			8 - window style
*/
function showTollTip(obj, sText)
{
	sShowCorner = "bottomMiddle";
	if(arguments[2] && arguments[2] != "")
		sShowCorner = arguments[2];
		
	sOpposideParam = "topMiddle";
	if(arguments[3] && arguments[3] != "")
		sOpposideParam = arguments[3];
		
	iBorder = 5;
	if(parseInt(arguments[4]) > 0)
		iBorder = parseInt(arguments[4]);
	
	iRadius = 10;
	if(parseInt(arguments[5]) > 0)
		iRadius = parseInt(arguments[5]);
	
	iPadding = 10;
	if(parseInt(arguments[6]) > 0)
		iPadding = parseInt(arguments[6]) ;
	
	sTextAlign = "center";
	if(arguments[7])
		sTextAlign = arguments[7];
	
	sWindowStyleName = "cream";
	if(arguments[8])
		sWindowStyleName = arguments[8];
	
	$(obj).qtip({
     content: sText,
     position: {
        corner: {
           tooltip: sShowCorner,
           target: sOpposideParam
        }
     },
     show: {
        when: false, 
        ready: true
     },
     hide: hideTolltip(),
     style: {
        border: {
           width: iBorder,
           radius: iRadius
        },
        padding: iPadding, 
        textAlign: sTextAlign,
        tip: true, 
        name: sWindowStyleName
     }
  });
  
  
  return;
}

function hideTolltip(obj)
{
	if($(obj).data("qtip")) 
		$(obj).qtip("destroy");
		
	return;
}


function showFloriristBlock()
{
	getSearchForm("footer_search_products");
	iHeight = $(window).height();
	$("#footer_search_products").css("top", (iHeight-430)+"px");
	$("#footer_search_products").css("display", "block");
	$("#footer_search_products").animate({"right": "0px"}, "slow");
	
	$("#close_footer_search").css("top", (iHeight-405)+"px");
	$("#close_footer_search").css("display", "block");
	$("#close_footer_search").animate({"right": "15px"}, "slow");
	
}


function closeFooterSearchBlock()
{
	$("#footer_search_products").css("display", "none");
	$("#footer_search_products").attr("style", "display: none;");
	$("#footer_search_products").html("");
	$("#close_footer_search").css("display", "none");
	
	return true;
}



function pause(ms)
{
  var date = new Date();
  var curDate = null;
  do { 
      curDate = new Date(); }
  while(curDate-date < ms);
}


function showProactiveHelp()
{
  if(lang == "ru")
  {
    sEnter = "Войти";
    sChatTitle = "Проактивный чат";
  }
  else if(lang == "en")
  {
    sEnter = "Enter";
    sChatTitle = "Live chat";
  }
  else if(lang == "ua")
  {
    sEnter = "Увійти";
    sChatTitle = "Живий чат";
  }
    
  sChat = "";
  sChat += "<div class='chat chat_"+lang+"'>";
	sChat += "<a href='javascript: void(0)' onclick='psBvBhow(); return false;'><span>"+sEnter+"</span></a>";
	sChat += "</div>";
  
  showDialod(sChat, sChatTitle, 250, 160);
  
  return;
}


/*function getAjaxProducts(iScroll)
{
  var url = "/ajax.php";
  var oAjaxData = new Object;
  var products_height = $("#products_list").height();

  if(iScroll > (products_height-200) && $("#ajax_page_num").html()!= "end")
  {
    oAjaxData['func'] = "getProductList";
    oAjaxData['lang'] = language;
    oAjaxData['page'] = $("ajax_page_num").val();
    
    $("#ajax_page_result").html("start");
    $.post(url, oAjaxData, function(data){
      if(parseInt(data) != 1)
      {
        $("#ajax_page_num").html((parseInt(oAjaxData['page'])+1));
        $("span#products_list").append(data);
        $("#ajax_page_result").html("stop");
        hideAjaxLoader();
        $(window).scrollTop(iScroll);
      }
      else
      {
        $("#ajax_page_num").html("end");
        hideAjaxLoader();
        $(window).scrollTop(iScroll);
      }
    });
  }
  else
    return;
}*/

function getAjaxProducts(iNum, sBlockId, iLoadImage)
{
  if(iNum == 0 && sBlockId == 0)
  {
    $("#all_products_button").remove();
    showAjaxLoader();
  }
  
  var url = "/ajax.php";
  var oAjaxData = new Object;
  
  oAjaxData['func']       = "getProductListBlock";
  oAjaxData['lang']       = language;
  oAjaxData['page']       = iNum;
  oAjaxData['block']      = sBlockId;
  oAjaxData['loadImages'] = iLoadImage;
  
  $.post(url, oAjaxData, function(data){
    if(parseInt(data) != 1)
    {
      if(iLoadImage == 1 && iNum > 0)
        $("span#"+sBlockId).html(data);
      else
        $("span#products_list").append(data);
    }
    hideAjaxLoader();
  });
}


/*function newDesign()
{
	if(checkCookie("was_shown"))
	{
		if(getCookie("was_shown") == "open")
		{
			$("#new_design").css("display", "block");
			$("#close_new_design").css("display", "block");
		}
		else if(getCookie("was_shown") == "closed")
		{
			$("#close_new_design").css("display", "none");
			$("#new_design").css("display", "none");
		}
	}
	else
	{
		$("#new_design").animate({opacity: 1,	height: 'toggle'}, 2000, function() {});
		$("#close_new_design").css("display", "block");
		setCookie("was_shown", "open");
	}
}*/

/*function closeNewDesign()
{
	setCookie("was_shown", "closed");
	$("#new_design").css("display", "none");
	$("#close_new_design").css("display", "none");
}*/

function setCookie(c_name,value,exdays)
{
	var exdate=new Date();
	exdate.setDate(exdate.getDate() + exdays);
	var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
	document.cookie=c_name + "=" + c_value;
}

function getCookie(c_name)
{
	var i,x,y,ARRcookies=document.cookie.split(";");
	for (i=0;i<ARRcookies.length;i++)
	{
	  x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
	  y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
	  x=x.replace(/^\s+|\s+$/g,"");
	  if (x==c_name)
	    {
	    	return unescape(y);
	    }
	  }
}

function checkCookie(cookieName)
{
	cookie = getCookie(cookieName);
	if (cookie != null && cookie != "" && cookie != 0)
  	return true;
	else
		return false;
}

function setactive(iStarNumber)
{
	if(iStarNumber == 0)
	{
		for( i = 1; i <= 5; i++)
			$("#star_"+i).attr("src", "/images/yellow_star.png");
	}
	else
	{
		for( i = 1; i <= iStarNumber; i++)
			$("#star_"+i).attr("src", "/images/green_star.png");
		for( i = (iStarNumber+1); i <= 5; i++)
			$("#star_"+i).attr("src", "/images/yellow_star.png");
	}
}

function selectrate(iStarNumber)
{
	for( i = 1; i <= iStarNumber; i++)
		$("#star_"+i).attr("src", "/images/green_star.png");
	for( i = (iStarNumber+1); i <= 5; i++)
		$("#star_"+i).attr("src", "/images/yellow_star.png");
	
	$('input[name=raiting]').val(iStarNumber);
	
	$("img[id^=star_]").each(function(){
		$(this).removeAttr("onmouseover");
		$(this).removeAttr("onmouseout");
	});
	
				
	if(iStarNumber <= 2)
		$("#complain_reason").css("display", "");
	else
		$("#complain_reason").css("display", "none");
}

function showToTop()
{
	$("#to_top").removeClass("to_top_hide");
	$("#to_top").addClass("to_top_show");
}

function hideToTop()
{
	$("#to_top").removeClass("to_top_show");
	$("#to_top").addClass("to_top_hide");
}

function toTop()
{
	if(navigator.userAgent.toLowerCase().indexOf('chrome') > -1)
		$('body').animate({ scrollTop: 0 }, 3000);
	else
		$(window).scrollTop(0);
}

function uhodorder(sSiteName)
{
	url = "/ajax.php";
	
	sName 		= jQuery("input[name=client_name]").val();
	sEmail 		= jQuery("input[name=client_email]").val();
	sPhone 		= jQuery("input[name=client_phone]").val();
	sComment 	= jQuery("textarea[name=client_description]").val();
	sError 		= "";
	
	if(sName == "")
	{
		jQuery("input[name=client_name]").css("border", "1px solid red");
		sError += "Поле 'Ваше имя' обязательно для заполнения \r\n";
	}
	else
		jQuery("input[name=client_name]").css("border", "1px solid #A5ACB2");
		
	if(sEmail == "")
	{
		jQuery("input[name=client_email]").css("border", "1px solid red");
		sError += "Поле 'Ваш E-Mail' обязательно для заполнения \r\n";
	}
	else
		jQuery("input[name=client_email]").css("border", "1px solid #A5ACB2");
		
	if(sPhone == "")
	{
		jQuery("input[name=client_phone]").css("border", "1px solid red");
		sError += "Поле 'Ваш контактный телефон' обязательно для заполнения";
	}
	else
		jQuery("input[name=client_phone]").css("border", "1px solid #A5ACB2");
		
	if(sError == "")
	{
		p = new Object;
		p['name'] 		= sName;
		p['email'] 		= sEmail;
		p['phone'] 		= sPhone;
		p['comment'] 	= sComment;
		p['func']			= "uhodZaMogilamiOrder";
		
		$.post(url, p, function(data){
			$("#uhod_order").css("display", "none");
			$("#uhod_order_button").css("display", "none");
			$("#uhod_result").html("Спасибо за Ваш заказ. Он будет обработан в кратчайшые строки и с Вами свяжется Наш менеджер." + data);
			$("#uhod_result").css("display", "block");
			}, "html");
	}
	else
	{
		alert(sError);
		return false;
	}
}


function uhodquestion(sSiteName)
{
	url = "/ajax.php";
	
	sName 		= jQuery("input[name=uhod_question_name]").val();
	sEmail 		= jQuery("input[name=uhod_question_email]").val();
	sComment 	= jQuery("textarea[name=uhod_question]").val();
	sError 		= "";
	
	if(sName == "")
	{
		jQuery("input[name=uhod_question_name]").css("border", "1px solid red");
		sError += "Поле 'Ваше имя' обязательно для заполнения \r\n";
	}
	else
		jQuery("input[name=uhod_question_name]").css("border", "1px solid #A5ACB2");
		
	if(sEmail == "")
	{
		jQuery("input[name=uhod_question_email]").css("border", "1px solid red");
		sError += "Поле 'Ваш E-Mail' обязательно для заполнения \r\n";
	}
	else
		jQuery("input[name=uhod_question_email]").css("border", "1px solid #A5ACB2");
		
	if(sComment == "")
	{
		jQuery("textarea[name=uhod_question]").css("border", "1px solid red");
		sError += "Поле 'Вопрос' обязательно для заполнения";
	}
	else
		jQuery("textarea[name=uhod_question]").css("border", "1px solid #A5ACB2");
		
	if(sError == "")
	{
		p = new Object;
		p['name'] 		= sName;
		p['email'] 		= sEmail;
		p['comment'] 	= sComment;
		p['func']			= "uhodZaMogilamiQuestion";
		
		$.post(url, p, function(data){
			$("#uhod_question").css("display", "none");
			$("#uhod_question_field").css("display", "none");
			$("#uhod_question_button").css("display", "none");
			$("#uhod_question_result").html("Спасибо за Ваш вопрос. Он будет обработан в кратчайшые строки и Вы получите ответ на Ваш email." + data);
			$("#uhod_question_result").css("display", "block");
			}, "html");
	}
	else
	{
		alert(sError);
		return false;
	}
}

function isNumber(n) {
  return !isNaN(parseFloat(n)) && isFinite(n);
}


function delivery(sType)
{
	$("#delivery_"+sType+"_button").hide("slow");
	$("#delivery_"+sType).show("slow");
	
	if(sType == "region")
	{
		$("#delivery_city").hide("slow");
		$("#delivery_city_button").show("slow");
	}
	else if(sType == "city")
	{
		$("#delivery_region").hide("slow");
		$("#delivery_region_button").show("slow");
	}
}

function closeDelivery(sType)
{
	$("#delivery_"+sType).hide("slow");
	$("#delivery_"+sType+"_button").show("slow");
}

/**
 * START функции для работы с поиском городов
 */
function changeStyle(sElementId, sCurrentStyle, sNewStyle, sDefaultText, bCheckText)
{
	if($("input[name=search_keyword]").val() == sDefaultText && bCheckText == true)
	{
		$("input[name=search_keyword]").attr("value", "");
		$("#"+sElementId).removeClass(sCurrentStyle);
		$("#"+sElementId).addClass(sNewStyle);
	}
	else
	{
		$("#"+sElementId).removeClass(sCurrentStyle);
		$("#"+sElementId).addClass(sNewStyle);
	}
}

function checkCityValue(sDefaultText)
{
	if($("#search_keyword").val()=="")
	{
		changeStyle('search_field', 'search_filed_active', 'search_filed_noactive', sDefaultText, false);
		$("#search_keyword").val(sDefaultText);
	}
	else
	{
		$("#all_cities span").click(function(){
			window.location.href = $(this).attr("href");
			$("#all_cities").remove();
			$("#cities_list").removeClass("cities_active");
			$("#cities_list").addClass("cities_noactive");
		});
	}
}


function selectCities(sCitiesBlock, sDefaultText)
{
	url = "/ajax.php";
	
	if($("span[id=ajax_loader]").html() == null)
		$("<span id='ajax_loader'><img src='/images/ajax-loader.gif' /></span>").insertAfter("#search_keyword");

	sKeyWord = $("#search_keyword").val();
	if(sKeyWord != "" && sKeyWord != sDefaultText)
	{
		$("#"+sCitiesBlock).removeClass("cities_active");
		$("#"+sCitiesBlock).addClass("cities_noactive");
			
		var oData 				= new Object;
		oData['key_word'] = sKeyWord;
		oData['lang'] 		= lang;
		oData['func'] 		= "selectCityByName";
		if($("input[name=nameBlock]").val() != "0")
			oData['block'] = $("input[name=nameBlock]").val();
		
		$.post(url, oData, function(data){
			$("#all_cities").remove();
			if(data != "")
			{
				$("#popup_window").height("400");
				$("#"+sCitiesBlock).html(data);
				$("#"+sCitiesBlock).removeClass("cities_noactive");
				$("#"+sCitiesBlock).addClass("cities_active");
				$('span[id=ajax_loader]').remove();
			}
			else
			{
				$("#popup_window").height("150");
				$('span[id=ajax_loader]').remove();
			}
		});
	}
	else
	{
		$("#all_cities").remove();
	}
}


function activeCity(obj)
{
	$("tr[id^=city_]").each(function(){
			$(this).removeClass("active_city");
			$(this).addClass("single_city");
		});
		$(obj).addClass("active_city");
		
	$("#search_keyword").removeAttr("onblur");
	$("#search_keyword").removeAttr("blur");
	$("#search_keyword").unbind("blur");
	$("#search_keyword").blur(function(){return false;});

}

function anyActiveCity()
{
	$("tr[id^=city_]").each(function(){
			$(this).removeClass("active_city");
			$(this).addClass("single_city");
		});
    
  if(language == "ru")
  {
    sText = "Введите название города";
  }
  else if(language == "en")
  {
    sText = "Enter the city name";
  }
	else if(language == "ua")
  {
    sText = "Введіть назву міста";
  }
  	
	$("#search_keyword").bind("blur", function(){
		checkCityValue(sText);
	});
}


function chooseCity(obj)
{
	sCityNick = $(obj).attr("name");
  if(site_name == "flora2000.ru" || site_name == "ru-flowers.com")
	  sLink = "/"+sCityNick;
  else if(language == "ua" || language == "en")
  	sLink = "/"+language+"/dostavka-cvetov-"+sCityNick;
 	else
 		sLink = "/dostavka-cvetov-"+sCityNick;
    
	$("#city_form").attr("action", sLink);
	$("#search_keyword").val($(obj).attr("city_name"));
	$("#all_cities").remove();
	$("#cities_list").removeClass("cities_active");
	$("#cities_list").addClass("cities_noactive");
  
  if(language == "ru")
  {
    sText = "Введите название города";
  }
  else if(language == "en")
  {
    sText = "Enter the city name";
  }
	else if(language == "ua")
  {
    sText = "Введіть назву міста";
  }
	
	$("#search_keyword").bind("blur", function(){
		checkCityValue(sText);
	});
	
	$("#submit_city").removeClass("big_gray_dutton");
	$("#submit_city").addClass("big_blue_dutton");
	
	$("#submit_city").removeAttr("onclick");
	$("#submit_city").removeAttr("click");
	$("#submit_city").unbind("click");
	$("#submit_city").click(function(){return true;});
	
	$("#city_form").removeAttr("onsubmit");
	$("#city_form").removeAttr("submit");
	$("#city_form").unbind("submit");
	$("#city_form").click(function(){return true;});
	
	if(arguments[1] == "submit")
		window.location.href = sLink;
	else
	{
		url = "/ajax.php";
		
		sBlock = arguments[1];
		oData = new Object;
		oData['city'] = sCityNick;
		oData['func'] = "setSearchCity";
		
		$.post(url, oData, function(data){
			$("#"+sBlock).html(data);
			$("#popup_window").dialog("close");
			if($("#popup_window_second").css("display") == "block")
			{
				currText = $("#popup_window_second .p_curr").html();
				if(currText == "грн" || currText == "uah")
					currency = "uah";
				else if(currText == "$" || currText == "usd")
					currency = "usd";
				else if(currText == "rur" || currText == "руб")
					currency = "rur";
				else if(currText == "eur" || currText == "€")
					currency = "eur"
				else if(currText == "gbp" || currText == "?")
					currency = "gbp"
				ajaxPriceUpdate (currency, currText);
			}
			ajaxSearch();
		});
	}
}
/**
 * END функции для работы с поиском городов
 */

function setCookie(c_name,value,exdays)
{
var exdate=new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
document.cookie=c_name + "=" + c_value;
}

function getCookie(c_name)
{
var i,x,y,ARRcookies=document.cookie.split(";");
for (i=0;i<ARRcookies.length;i++)
{
  x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
  y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
  x=x.replace(/^\s+|\s+$/g,"");
  if (x==c_name)
    {
    return unescape(y);
    }
  }
}

function showHidePhones()
{
	var sShow = $("#all_phones_block").css("display");
	if(sShow == "block")
		$("#all_phones_block").hide('slow');
	else if(sShow == "none")
	{
		$("#all_phones_block").css("position", "absolute");
		$("#all_phones_block").css("z-index", "1000");
		$("#all_phones_block").css("border", "1px dotted black");
		$("#all_phones_block").css("background-color", "#ECFFF2");
		$("#all_phones_block").css("margin-left", "10px");
		$("#all_phones_block").css("width", "250px");
		$("#all_phones_block").show('slow');
	}
		
	return true;
}


function showMap(iIdBlock)
{
  var sShow = $("#yangex_map"+iIdBlock).css("display");
	if(sShow == "block")
		$("#yangex_map"+iIdBlock).hide('slow');
	else if(sShow == "none")
	{
		$("#yangex_map"+iIdBlock).css("position", "absolute");
		$("#yangex_map"+iIdBlock).css("z-index", "1000");
		$("#yangex_map"+iIdBlock).css("border", "1px dotted black");
		$("#yangex_map"+iIdBlock).css("background-color", "#ECFFF2");
		$("#yangex_map"+iIdBlock).css("margin-left", "10px");
		$("#yangex_map"+iIdBlock).css("width", "600px");
		$("#yangex_map"+iIdBlock).show('slow');
	}
		
	return true;
}


function showAjaxLoader()
{
  $("div#ajax_loader").removeClass("hide_ajax_loader");
  $("div#ajax_loader").addClass("show_ajax_loader");
}

function hideAjaxLoader()
{
  $("div#ajax_loader").removeClass("show_ajax_loader");
  $("div#ajax_loader").addClass("hide_ajax_loader");
}


function getLinkForFriend(iProductId, sDeliveryCity)
{
  if(language=="ru")
    var sTitle = "Ссылка другу";
  else if(language=="ua")
    var sTitle = "Посилання другу";
  else if(language=="en")
    var sTitle = "Link for friend";
    
  $.get("/ajax.php",{product: iProductId, city: sDeliveryCity, lang: language, func: "getFriendLink"}, function(data){
    showDialod(data, sTitle, 500, 100);
  });
  return;
}


//arguments
// 1 - window message - required
// 2 - window title 	- required
// 3 - window width 	- not required
// 4 - window height 	- not required
function showDialod(sMessage)
{
	width = 600;
	if(parseInt(arguments[2]) > 0)
		width = parseInt(arguments[2]);
	
	height = 300;
	if(parseInt(arguments[3]) > 0)
		height = parseInt(arguments[3]);
		
	title = "Помилка";
	if(arguments[1])
		title = arguments[1];
		
	sDivId = "popup_window";
	if(arguments[4])
		sDivId = arguments[4];
		
	$("#"+sDivId).html(sMessage);
	$("#"+sDivId).dialog({ 
												maxWidth: 600, 
												width: width, 
												title: title, 
												maxHeight: 600, 
												height: height, 
												show: 'slide' 
											});
}


function showChooseRegionPopup(sBlockId)
{
  if(language=="ru")
    var sTitle = "Поиск города доставки";
  else if(language=="ua")
    var sTitle = "Пошук міста доставки";
  else if(language=="en")
    var sTitle = "Search delivery city";
    
  iShowFalseSearch = 1;
  if(arguments[1] == 'false')
    iShowFalseSearch = 0;
    
  if(sBlockId == undefined)
	{  
	  $.get("/ajax.php",{lang: language, func: "getSearchCitiesForm",city:iShowFalseSearch}, function(data){
	    showDialod(data, sTitle, 513, 150);
	    var obj = document.getElementById("search_keyword");
	    obj.focus();
	  });
  }
  else
  {
  	$.get("/ajax.php",{lang: language, func: "getSearchCitiesForm", block: sBlockId,city:iShowFalseSearch}, function(data){
	    showDialod(data, sTitle, 513, 150);
	    var obj = document.getElementById("search_keyword");
	    obj.focus();
	  });
  }
}


function addAllProductsButton()
{
  if(index_page == "1")
  {
    if(lang == "ru")
      sText = 'Просмотреть все букеты';
    else if(lang == "ua")
      sText = "Переглянути усі букети";
    else
      sText = "Show all boquets";
  }
  else
  {
    if(lang == "ru")
      sText = 'Cмотреть все букеты';
    else if(lang == "ua")
      sText = "Дивитись усі букети";
    else
      sText = "Watch all boquets";
  }
  
  sContent = '<div class="cl"></div>'  
  sContent += '<br /><br /><center><span id="all_products_button">';
  sContent += '<a href="javascript: void(0);" onclick="getAjaxProducts(0, 0, 1);" style="text-decoration: none;">';
  sContent += '<div class="button_310" style="height: 40px;">';
  sContent += '<div class="button_left">&nbsp;</div>';
  sContent += '<div class="button_center_300">';
  sContent += sText;
  sContent += '</div>';
  sContent += '<div class="button_right">&nbsp;</div>';
  sContent += '</div>';
  sContent += '</a>';
  sContent += '</span></center><br /><br />';
  
  $("span#products_list").after(sContent);

  
  return;
}


function showSelectBoquetPopUp(isSearchForm)
{
  if(parseInt(isSearchForm) == 1)
    getSearchForm('search_form');
  else if(parseInt(isSearchForm) == 2)
    addConditions('search_form');
  
  iDocumentWidth  = document.body.offsetWidth;
  iMonitorWidth   = window.screen.width;
  iDocumentHeight = document.body.offsetHeight;
  iScrollTop      = $(window).scrollTop();
  
  $("#search_form").css("width", "260px");
  
  iSearchFormWidth = $("#search_form").width();
  
  $("#search_form").css("background-color", "#F0F39C");
  $("#search_form").css("margin-left", ((iDocumentWidth/2)-(iSearchFormWidth))+"px");
  $("#search_form").css("border", "1px solid #000000");
  $("#search_form").css("border-radius", "10px");
  $("#search_form").css("z-index", "500");
  $("#search_form").css("position", "absolute");
  iTop = parseInt(iScrollTop)+170;
  sTop = iTop+"px";
  $("#search_form").css("margin-top", sTop);
  
  $("#close_search_block").css("margin-left", (((iDocumentWidth/2)-(iSearchFormWidth/2))+(iSearchFormWidth/2)-20)+"px");
  $("#close_search_block").css("margin-top", (iScrollTop+180)+"px");
  
  
  $("#search_products_main").css("width", iMonitorWidth);
  $("#search_products_main").css("height", iDocumentHeight);
  
  
  $("#search_products_main").css("display", "block");
  $("#search_form").css("display", "block");
  $("#close_search_block").css("display", "block");
}


function closeSearchProductPopUp()
{
  $("#search_form").html("");
  $("#search_form").css("display", "none");
  $("#close_search_block").css("display", "none");
  $("#search_products_main").css("display", "none");
}

function getSearchForm(sSearchFormContainerId)
{
  sPage = "/ajax.php";
  $.get(sPage, {func: "getSearchForm", lang: language, change: "ajaxSearch"}, function(oResult){
    $("#"+sSearchFormContainerId).html(oResult);
    return;
  });
  
  return;
}


function ajaxSearch()
{
  sPage = "/ajax.php";
  addSearchProductsLoader();
  oParams = getSearchParams('object');
  oParams['func'] = 'getSearchProductsCount';
  oParams['lang'] = language;
  
  $.post(sPage, oParams, function(data){
    $("#button").html(data);
  });
  
  return;
}


function getSearchParams(sReturnType)
{
  iFlowerId   = parseInt($("select[name=include_flowers] :selected").val());
  //sColors     = $("select[name=flower_colors] option:selected").val();
  fPriceFrom  = parseFloat($("input[name=min_price]").val());
  fPriceTo    = parseFloat($("input[name=max_price]").val());
  //sBoquetSize = $("select[name=boquet_sizes] :selected").val();
  iPovodId    = parseInt($("select[name=boquet_povods] :selected").val());
  

  if(sReturnType == "object")
  {
    oData = new Object;
    
    if(iFlowerId > 0)
      oData['flower_id'] = iFlowerId;
    
    //if(sColors != "")
    //  oData['color_name'] = sColors;
    
    if(fPriceFrom > 0)
      oData['min_price'] = fPriceFrom;
    
    if(fPriceTo > 0)
      oData['max_price'] = fPriceTo;
    
    //if(sBoquetSize != "")
    //  oData['boquet_size'] = sBoquetSize;
    
    if(iPovodId > 0)
      oData['povod_id'] = iPovodId;
      
    return oData;
  }
  else if(sReturnType == "string")
  {
    var iFirstElement = 0;
    var sReturnString = "";
    
    if(iFlowerId > 0)
    {
      if(iFirstElement == 0)
      {
        sReturnString += "flower_id="+iFlowerId;
        iFirstElement = 1;
      }
      else
        sReturnString += "&flower_id="+iFlowerId;
    }
    
    //if(sColors != "")
    // {
    //  if(iFirstElement == 0)
    //  {
    //    sReturnString += "color_name="+sColors;
    //    iFirstElement = 1;
    //  }
    //  else
    //    sReturnString += "&color_name="+sColors;
    //}
    
    if(fPriceFrom > 0)
    {
      if(iFirstElement == 0)
      {
        sReturnString += "min_price="+fPriceFrom;
        iFirstElement = 1;
      }
      else
        sReturnString += "&min_price="+fPriceFrom;
    }
    
    if(fPriceTo > 0)
    {
      if(iFirstElement == 0)
      {
        sReturnString += "max_price="+fPriceTo;
        iFirstElement = 1;
      }
      else
        sReturnString += "&max_price="+fPriceTo;
    }
    
    //(sBoquetSize != "")
    //{
    //  if(iFirstElement == 0)
    //  {
    //    sReturnString += "boquet_size="+sBoquetSize;
    //    iFirstElement = 1;
    //  }
    //  else
    //    sReturnString += "&boquet_size="+sBoquetSize;
    //}
    
    if(iPovodId > 0)
    {
      if(iFirstElement == 0)
      {
        sReturnString += "povod_id="+iPovodId;
        iFirstElement = 1;
      }
      else
        sReturnString += "&povod_id="+iPovodId;
    }
    
    return sReturnString;
  }
}

function addSearchProductsLoader()
{
  sContent = "<img src='/img/ajax-loader.gif' style='padding-left: 30%'>";
  $("#result_count_block").html(sContent);
}


function showSelectedProducts()
{
  sSearchParams = getSearchParams('string');
  sHref = "/"+lang+"/search_result?"+sSearchParams;
  window.location.href = sHref;
}


function getEditedParam(sBlockId, sParamName, sLang)
{
  sPath         = "/ajax.php";
  sCurrentValue = $("input[name="+sBlockId+"]").val();
  
  $.get(sPath, {func: "getEditedParam", sParam: sParamName, sLang: sLang, sValue: sCurrentValue}, function(oResult){
    $("#"+sBlockId).html(oResult);
  });
}


function changeSearchRequestFlowers()
{
  iFlowerId = parseInt($("select[name=include_flowers] :selected").val());
  $("input[name=flower_id]").val(iFlowerId);
  
  reloadSearch();
}


function changeSearchRequestColor()
{
  sColorName = $("select[name=flower_colors] :selected").val();
  $("input[name=color_name]").val(sColorName);
  
  reloadSearch();
}


function changeSearchRequestPovod()
{
  iPovodId = parseInt($("select[name=boquet_povods] :selected").val());
  $("input[name=povod_id]").val(iPovodId);
  
  reloadSearch();
}


function changeSearchRequestSize()
{
  sSizeName = $("select[name=boquet_sizes] :selected").val();
  $("input[name=boquet_size]").val(sSizeName);
  
  reloadSearch();
}


function reloadSearch()
{
  sRequestString = getNewSearchParams();
  sHref = "/"+lang+"/search_result?"+sRequestString;
  window.location.href = sHref;
}


function getNewSearchParams()
{
  iFlowerId   = parseInt($("input[name=flower_id]").val());
  //sColors     = $("input[name=color_name]").val();
  fPriceFrom  = parseFloat($("input[name=min_price]").val());
  fPriceTo    = parseFloat($("input[name=max_price]").val());
  //sBoquetSize = $("input[name=boquet_size]").val();
  iPovodId    = parseInt($("input[name=povod_id]").val());
  
  var iFirstElement = 0;
  var sReturnString = "";
  
  if(iFlowerId > 0)
  {
    if(iFirstElement == 0)
    {
      sReturnString += "flower_id="+iFlowerId;
      iFirstElement = 1;
    }
    else
      sReturnString += "&flower_id="+iFlowerId;
  }
  
  //if(sColors != "")
  // {
  //  if(iFirstElement == 0)
  //  {
  //    sReturnString += "color_name="+sColors;
  //    iFirstElement = 1;
  //  }
  //  else
  //    sReturnString += "&color_name="+sColors;
  //}
  
  if(fPriceFrom > 0)
  {
    if(iFirstElement == 0)
    {
      sReturnString += "min_price="+fPriceFrom;
      iFirstElement = 1;
    }
    else
      sReturnString += "&min_price="+fPriceFrom;
  }
  
  if(fPriceTo > 0)
  {
    if(iFirstElement == 0)
    {
      sReturnString += "max_price="+fPriceTo;
      iFirstElement = 1;
    }
    else
      sReturnString += "&max_price="+fPriceTo;
  }
  
  //if(sBoquetSize != "")
  //{
  //  if(iFirstElement == 0)
  //  {
  //    sReturnString += "boquet_size="+sBoquetSize;
  //    iFirstElement = 1;
  //  }
  //  else
  //    sReturnString += "&boquet_size="+sBoquetSize;
  //}
  
  if(iPovodId > 0)
  {
    if(iFirstElement == 0)
    {
      sReturnString += "povod_id="+iPovodId;
      iFirstElement = 1;
    }
    else
      sReturnString += "&povod_id="+iPovodId;
  }
  
  return sReturnString;
}

function deleteSearchParam(sParamName)
{
  $("input[name="+sParamName+"]").val("");
  
  reloadSearch();
}

function changeSearchRequestPrice(sPriceName)
{
  sNewVal = $("input[name="+sPriceName+"][type=text]").val();
  $("input[name="+sPriceName+"][type=hidden]").val(sNewVal);
  
  reloadSearch();
}


function addConditions(sBlockId)
{
  iFlowerId   = parseInt($("input[name=flower_id]").val());
  //sColors     = $("input[name=color_name]").val();
  fPriceFrom  = parseFloat($("input[name=min_price]").val());
  fPriceTo    = parseFloat($("input[name=max_price]").val());
  //sBoquetSize = $("input[name=boquet_size]").val();
  iPovodId    = parseInt($("input[name=povod_id]").val());
  
  oData = new Object;
  oData['func'] = "getAddConditionForm";
  oData['lang'] = language;
  
  if(iFlowerId == 0)
    oData['flower_id'] = 1;
  else
    oData['flower_id'] = 0;
    
  //if(sColors == "")
  //  oData['color_name'] = 1;
  //else
  //  oData['color_name'] = 0;
    
  if(fPriceFrom == 0)
    oData['min_price'] = 1;
  else
    oData['min_price'] = 0;
    
  if(fPriceTo == 0)
    oData['max_price'] = 1;
  else
    oData['max_price'] = 0;
    
  //if(sBoquetSize == "")
  //  oData['boquet_size'] = 1;
  //else
  //  oData['boquet_size'] = 0;
  
  if(iPovodId == 0)
    oData['povod_id'] = 1;
  else
    oData['povod_id'] = 0;
    
  sPath         = "/ajax.php";
  
  $.post(sPath, oData, function(oResult){
    $("#"+sBlockId).html(oResult);
  });
}


function addConditionsToSearch()
{
  iFlowerId   = parseInt($("input[name=flower_id]").val());
  //sColors     = $("input[name=color_name]").val();
  fPriceFrom  = parseFloat($("input[name=min_price][type=hidden]").val());
  fPriceTo    = parseFloat($("input[name=max_price][type=hidden]").val());
  //sBoquetSize = $("input[name=boquet_size]").val();
  iPovodId    = parseInt($("input[name=povod_id]").val());
  
  if(iFlowerId == 0)
    $("input[name=flower_id]").val($("select[name=include_flowers] :selected").val());
  //if(sColors == "")
  //  $("input[name=color_name]").val($("select[name=flower_colors] :selected").val());
  //if(sBoquetSize == "")
  //  $("input[name=boquet_size]").val($("select[name=boquet_sizes] :selected").val());
  if(iPovodId == 0)
    $("input[name=povod_id]").val($("select[name=boquet_povods] :selected").val());
    
  if(fPriceFrom == 0)
    $("input[name=min_price][type=hidden]").val($("input[name=min_price][type=text]").val());
  if(fPriceTo == 0)
    $("input[name=max_price][type=hidden]").val($("input[name=max_price][type=text]").val());
    
  reloadSearch();
}


function showNeedBouquetForm(sContent)
{
  sPath = "/ajax.php";
  if(lang == "ru")
    sTitle = "Заявка на букет";
  else if(lang == "ua")
    sTitle = "Заявка на букет";
  else if(lang == "en")
    sTitle = "Order for bouquet";
  
  if(sContent == undefined)
  	sIndertInBlock = "";
 	else
 		sIndertInBlock = sContent;
    
  $.get(sPath, {func: "getNeedBouquetForm", sLang: lang, insert: sIndertInBlock}, function(oResult){
    showDialod(oResult, sTitle, 370, 330);
  });
}

function clearBlock(sBlockName, sDefaultText)
{
  sText = $(sBlockName).val();
  if(sText == sDefaultText)
  {
    $(sBlockName).val("");
    $(sBlockName).css("color", "#000000");
  }
}

function addBlockValue(sBlockName, sDefaultText)
{
  sText = $(sBlockName).val();
  if(sText == "")
  {
    $(sBlockName).val(sDefaultText);
    $(sBlockName).css("color", "gray");
  }
}


function saveOrderForBouquet(sDefaultDescription)
{
  if(lang == "ru")
  {
    sNoDescription = "Пожалуйста заполните поле описание.";
    sNoConnection = "Пожалуйста заполните поле как с Вами связатся.";
    sSentOrder = "Спасибо за заявку.";
  }
  else if(lang == "ua")
  {
    sNoDescription = "Будь ласка заповніть поле опис.";
    sNoConnection = "Будь ласка заповніть поле як з Вами зв'язатися.";
    sSentOrder = "Дякуємо за заявку.";
  }
  else if(lang == "en")
  {
    sNoDescription = "Please fill in the description.";
    sNoConnection = "Please fill in as you to contact.";
    sSentOrder = "Thanks for the request.";
  }
  
  sOrderDescription = $("textarea[name=order_description]").val();
  if(sOrderDescription == "" || sOrderDescription == sDefaultDescription)
  {
    alert(sNoDescription);
    return false;
  }
  
  sOrderConnection = $("input[name=order_connect]").val();
  if(sOrderConnection == "")
  {
    alert(sNoConnection);
    return false;
  }
  sPath = "/ajax.php";
  
  $.get(sPath, {func: "saveOrderForm", description: sOrderDescription, connect: sOrderConnection, lang: language}, function(oResult){
    window.location.href = window.location.href;
  });
}

function checkCountry()
{
  if($("select[name=country_name]").val() == "other")
  {
    if(lang == "ru")
      sEnterCountry = "Введиде страну";
    else if(lang == "ua")
      sEnterCountry = "Введіть країну";
    else if(lang == "en")
      sEnterCountry = "Enter country";
      
    sInsert = "<tr id='input_country'>";
    sInsert += "<td>";
    sInsert += sEnterCountry;
    sInsert += "</td>";
    sInsert += "<td>";
    sInsert += "<input name='enter_country' type='text'>";
    sInsert += "</td>";
    sInsert += "</tr>";
    
    $(sInsert).insertAfter("#country");
    $("input[name=save_data]").val(1);
  }
  else if($("select[name=country_name]").val() == "")
  {
    $("input[name=save_data]").val(0);
    $("#input_country").remove();
    
    if(lang == "ru")
      sChoose = "Выберите страну";
    else if(lang == "ua")
      sChoose = "Вибериберіть країну";
    else
      sChoose = "Choose country";
    
    alert(sChoose);
    return false;
  }
  else
  {
    $("input[name=save_data]").val(1);
    $("#input_country").remove();
  }
}


function showSocialRegistrationBlock()
{
  sPath = "/ajax.php";
  if(language == "ru")
  {
    sTitle = "Войти используя социалную сеть";
  }
  else if(language == "ua")
  {
    sTitle = "Увійти використовуючи соціальну мережу";
  }
  else if(language == "en")
  {
    sTitle = "Login using social accaunt";
  }
  
  $.get(sPath, {func: "getSocialLinksToLogin", lang: language}, function(sResult){
    showDialod(sResult, sTitle, 300, 180);
  });
}

function changeImage(obj, sImagePath)
{
  obj.src = sImagePath;
  return;
}


function socialLogin(sSocialType)
{
	var sLink = "/";
	if(arguments[1])
		sLink = arguments[1];
		
  if(sSocialType == "vk")
  {
    $("#socal_registration").html("<center><div id='vk_auth'></div></center>");
  	VK.Widgets.Auth("vk_auth", {width: "200px", authUrl: '/developers.php?o=-1&p=Auth', onAuth: function(data) 
      {
  		  loginFromVkontakte(data, sLink);
      } 
  	});
  }
  else if(sSocialType == "fb")
  {
    loginFromFacebook(sLink);
  }
  else if(sSocialType == "tw")
  {
    alert("Tw");
  }
  
  return;
}

function loginFromVkontakte(oData, sLink)
{
	sPath = "/ajax.php";
 	$.get(sPath, {
 	                uid: oData['uid'], 
                  first_name: oData['first_name'],
                  last_name: oData['last_name'],
                  func: "vkLogin"
                }, 
        function(oResult){ 
     		if(oResult == 'success')
    			window.location.href = sLink;
    		else
    			alert(oResult);
 	});
  
  return;
}


function loginFromFacebook(sLink)
{
	FB.api('/me', function(response) {
		var p = new Object;
		p['first_name']	= response.first_name;
		p['last_name'] 	= response.last_name;
		p['email']			= response.email;
		p['uid']				= response.id;
		p['gender']			= response.gender;
		p['birth_date']	= response.birthday;
		p['func']			  = "fbLogin";
		
    makeLoginFromFacebook(p, sLink);
 	});
}

function makeLoginFromFacebook(oData, sLink)
{
	sPath = "/ajax.php";
 	$.post(sPath, oData, 
        function(oResult){ 
     		if(oResult == 'success')
    			window.location.href = sLink;
    		else
    			alert(oResult);
 	});
  
  return;
}


function shawAllProductsInCategory(obj, sShawBlockId)
{
  $("#"+sShawBlockId).attr("style", "");
  $(obj).remove();
}


function loadSocialRegistrationBlock(sBlockId)
{
  sPath = "/ajax.php";
  
  $.get(sPath, {func: "getSocialLinksToLogin", lang: language}, function(sResult){
    $("#"+sBlockId).html(sResult);
  });
}

var iBanner = 0;
function rotateBanners()
{
	iBanner++;
	
	sBlockId = "#banners";
	banner1 = "<a href='http://www.ufl.ua/samie_bespoleznie_podarki'><img src='/img/banner1.gif'></a>";
	banner2 = "<a href='http://flower-show.com.ua/2011/09/01/vtorojj_floristicheskijj_korporativ_flower_party.html'><img src='/img/banner2.jpg'></a>";
	
	if(iBanner == 1)
	{
		$(sBlockId).html(banner1);
		setTimeout("rotateBanners()", 5000);
	}
	else if(iBanner == 2)
	{
		$(sBlockId).html(banner2);
		setTimeout("rotateBanners()", 5000);
	}
	else
	{
		iBanner = 0;
		rotateBanners();
	}
}


function closeSocial()
{
	$("#social_links_block").css("display", "none");
	return true;
}


function getUserOwnOrderBlock()
{
	sPath = "/ajax.php";
	sSearchParams = getSearchParams('string');
	
	$.get(sPath, {func: "getUserFormData", lang: language, sParams: sSearchParams}, function(sResult){
    showNeedBouquetForm(sResult);
  });
}


function showAddReviewForm()
{
	sPath = "/ajax.php";
	if(language == "ru")
  {
    sTitle = "Оставить отзыв";
  }
  else if(language == "ua")
  {
    sTitle = "Залишити відгук";
  }
  else if(language == "en")
  {
    sTitle = "Send review";
  }
	
	$.get(sPath, {func: "getReviewForm", lang: language}, function(sResult){
		showDialod(sResult, sTitle, 450, 400);
	});
}


function loadFullContent(
													page_id, 
													cat_id, 
													flower_group_filter_id,
													povod_filter_id,
													page,
													flower_group_filter_name
												)
{
	sPath = "/ajax.php";
	
	oData = new Object;
	oData['page_id'] 								= page_id;
	oData['cat_id'] 								= cat_id;
	oData['flower_group_filter_id'] = flower_group_filter_id;
	oData['povod_filter_id'] 				= povod_filter_id;
	oData['page'] 									= page;
	oData['func']										= "getOtherFlowers";
	oData['start']									= 16;
	oData['end']										= 200;
	oData['lang']										= language;
	oData['flower_group_filter_name'] = flower_group_filter_name;
	
	$("#show_all_button_div").html('<img src="/img/ajax-loader.gif" />');
	
	$.post(sPath, oData, function(sResult){
		if(sResult == '1')
		{
			$("#show_all_button_div").remove();
		}
		else
		{
			$("#products_list").append(sResult);
			$("#show_all_button_div").remove();
		}
	});
	
	return true;
}

function getSocialBlock()
{
    sPath = "/ajax.php";
    
    p = "func=getSocialBlock";
    $.post(sPath, p, function(sResult){
       $("#social_links_block").html(sResult); 
       $("#social_links_block").css('width','140px');
	   $("#social_links_block").css('background-color','#EEE');
	   $("#social_links_block").css('border','1px solid #EEE');
    });
}


function showPaymentData(iPaymentId)
{
	sPath = "/ajax.php";
	
	if(language == "ru")
	{
		sTitle = "Описание оплаты";
	}
	else if(language == "ua")
	{
		sTitle = "Опис оплати";
	}
	else if(language == "en")
	{
		sTitle = "Payment description";
	}
	
	$.get(sPath, {func: "getPaymentDescription", payment_id: iPaymentId, lang: language}, function(sResult){
		sText = '<div style="width: 100%;"><div style="float: left; width: 30%"><img src="/images/payments_logo/pi_'+iPaymentId+'.gif" /></div><div>'+sResult+'</div></div>';
		showDialod(sText, sTitle, 700, 400);
	});
}


function changeProductImage(sChoosenImage, iProduct, obj)
{
	showImageLoader(obj);
	sImageBlock = 'tovar_large_pic';
	sPicturesBlock = 'product_small_pictures_block';
	sPath = "/ajax.php";
	var sImage = "";
	
	$.get(sPath, {func: "getLargePicture", image: sChoosenImage, product: iProduct}, function(sResult){
		sImage = sResult;
		$.get(sPath, {func: "getPicturesBlock", image: sChoosenImage, product: iProduct}, function(sResultData){
			sImagesBlock = sResultData;
			$('#'+sPicturesBlock).html(sImagesBlock);
			$('#'+sImageBlock).html(sImage);
			hideImageLoader();
		});
	});
	
	return true;
}


function showImageLoader(obj)
{
	$iLeft = $(obj).offset().left;
	$iLeft = $iLeft + (55/2 - 35/2);
	$iTop = $(obj).offset().top;
	$iTop = $iTop + (55/2 - 35/2);
	
	$("#image_loader").css("left", $iLeft+"px");
	$("#image_loader").css("top", $iTop+"px");
	$("#image_loader").css("display", "block");
}

function hideImageLoader()
{
	$("#image_loader").css("display", "none");
}


function showImagesViewBlock(iProductId, sProductName)
{
	sPath = "/ajax.php";
	
	$.get(sPath, {product_id: iProductId, func: "getImagesViewBlock"}, function(sResult){
		showDialod(sResult, sProductName, 550, 500, "popup_window_second");
	});
}

function setActivePreviewPicture(sActive, iProductId)
{
	sPath = "/ajax.php";
	
	$.get(sPath, {product_id: iProductId, func: "getActivePreviewPicture", active: sActive}, function(sResult){
		$("#photos_block").html(sResult)
	});
}


function showSiteMapBlock(iBlockNum)
{
	sImage = "<img src='/images/minus.gif' onclick='hideSitemapBlock("+iBlockNum+")' style='margin-left: -15px; cursor: pointer' />";
	$("span[name=root_item_"+iBlockNum+"]").html(sImage);
	$("#tree_"+iBlockNum).show("slow");
}

function hideSitemapBlock(iBlockNum)
{
	sImage = "<img src='/images/plus.gif' onclick='showSiteMapBlock("+iBlockNum+")' style='margin-left: -15px; cursor: pointer' />";
	$("span[name=root_item_"+iBlockNum+"]").html(sImage);
	$("#tree_"+iBlockNum).hide("slow");
}


function redirectToColor()
{
	sProductId = $("select[name=color] option:selected").attr("id");
	if(sProductId != "" && sProductId!=undefined)
	{
		iProductId = sProductId.replace("item_", "");
		if(parseInt(iProductId) > 0)
		{
			if(language == "ru")
				window.location.href = '/id/'+parseInt(iProductId);
			else
				window.location.href = '/'+language+'/id/'+parseInt(iProductId);
		}
		else
			return false;
	}
	else
		return false;
}


function showCheckOrderForm()
{
	sPath = "/ajax.php";
	
	if(language == "ru")
	{
		sTitle = "Проверить состояние заказа";
	}
	else if(language == "ua")
	{
		sTitle = "Перевірити статус замовлення";
	}
	else if(language == "en")
	{
		sTitle = "Check order status";
	}
	
	$.get(sPath, {func: "getCheckOrderForm", lang: language}, function(sResult){
		showDialod(sResult, sTitle,340,120);
	});
}

function checkOrderStatus()
{
	sPath = "/ajax.php";
	iOrderId = parseInt($("input[name=order_id]").val());
	
	if(lang == "ua")
	{
		sOrderError = "Введіть коректне значення номеру заказу!";
	}
	else if(lang == "ru")
	{
		sOrderError = "Введите правильное значение номера заказа!";
	}
	else if(lang == "en")
	{
		sOrderError = "Enter correct order number!";
	}
	
	if(iOrderId <= 0)
	{
		alert(sOrderError);
		return false;
	}
	
	$.get(sPath, {func: "getOrderStatus", order: iOrderId}, function(sResult){
		$("#order_check_result").html(sResult);
	});
	
}


function showLoginBlock()
{
	sPath = "/ajax.php";
	$.get(sPath, {func: "getAjaxLoginBlocks"}, function(sResult){
		$(sResult).insertBefore("#ajax_login_place");
		$("#ajax_login_place").remove();
	});
}


function loginMePlease()
{
	sEmail = $("input[name=user_email]").val();
	sPassword = $("input[name=user_password]").val();
	
	if(lang == "ua")
	{
		sLoginError = "Не приавильний Email або пароль!";
		sNotEmail 	= "Введіть Ваш Email";
		sNotPasswd 	= "Введіть Ваш пароль";
	}
	else if(lang == "ru")
	{
		sLoginError = "Не верный Email или пароль!";
		sNotEmail 	= "Введите Ваш Email";
		sNotPasswd 	= "Введите Ваш пароль";
	}
	else if(lang == "en")
	{
		sLoginError = "Enter correct Email and password!";
		sNotEmail 	= "Enter your Email";
		sNotPasswd 	= "Enter your password";
	}
	
	if(sEmail == "")
	{
		alert(sNotEmail);
		return false;
	}
	else if(sPassword == "")
	{
		alert(sNotPasswd);
		return false;
	}
	
	sPath = "/ajax.php";
	
	$.get(sPath, {func: "ajaxLoginUser", email: sEmail, passwd: sPassword}, function(sResult){
		if(parseInt(sResult) == 1)
		{
			//sSite = window.location.href;
			window.location.href = 'http://my.ufl.ua/'+language+'/upage/user_orders';
		}
		else
		{
			alert(sLoginError);
			return false;
		} 
	});
}


function strstr( haystack, needle, bool ) 
{	
	var pos = 0;
	
	pos = haystack.indexOf( needle );
	if( pos == -1 )
	{
		return false;
	} 
	else
	{
		if(bool)
		{
			return haystack.substr(0, pos);
		} 
		else
		{
			return haystack.slice(pos);
		}
	}
}


function showAllCities()
{
	var p = new Object;
	p['func'] = "getAllCountryCities";
	
	$.post("/ajax.php", p, function(oResult){
		aData = $.parseJSON(oResult);
		showDialod(aData['content'], aData['title'], 600, 500);
	});
}

