pform_options = {
    addWarningElements: false,
    addWarningsOnInit: false
};

function createCookie(name,value,days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        var expires = "; expires="+date.toGMTString();
    }
    else var expires = "";
    document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);  
    }
    return null;
}

function eraseCookie(name) {
    createCookie(name,"",-1);
}

function number_format(letter, number) {
    var spec_chars=new Array(0,9,35,36,37,39,46,27,13);
    var valid=true;
    for (i=0;i<spec_chars.length;i++) {
        if (letter.keyCode==spec_chars[i]) valid=false;
    }
    if (valid) {
        number.value=formaz2(number.value);
    }
}

function formaz2 (szam) {
    sz=szam.toString().replace(/ /g,'');
    szindex=sz.search(/[.,]/);
    if (szindex>-1) k=szindex;
    else k=sz.length;
    sz2='';
    j=0;
    for (i=k;i>0;i--) {
        sz2=sz.charAt(i-1)+sz2;
        if (j==2 && i>1) {
            sz2=' '+sz2;
            j=-1;
        }
        j++;
    }
    if (szindex!=-1)  sz2=sz2+'.';
    j=0;
    for (i=k+1;i<sz.length;i++) {
        if (sz.charAt(i).search(/[.,]/)==-1) sz2=sz2+sz.charAt(i);
        if (j==2 && i<sz.length-1) {
            sz2=sz2+' ';
            j=-1;
        }
        j++;
    }
    return sz2;
}

function populate_select(id, options, selected)
{
    var html='';
    for (var i in options) {
        var selected_html = i==selected ? ' selected ' : '';
        html += '<option value="'+i+'" '+selected_html+'">'+options[i]+'</option>';
    }
    $('#'+id).html(html);
}

function ajax_count_search_results() 
{
    $.ajax({
        url: 'cars/ajax_count_search_results',
        data: $('#search_form').serialize(),
        type: 'post',
        success: function(response) {
            eval('json_response = '+response);
            $('#search_button span').html('Keresés ('+json_response.counter+' találat)');
        }
    })
}

function send_url_segments(e, fields)
{
    var $form = $(e).parents('form');
    var action= $form.attr('action');
    
    var new_action = action+'/';
    for (var i=0; i<fields.length; i++) {
        var val = $('#'+fields[i], $form).val();
        new_action += (val+'/');
    }
    $form.attr('action', new_action);
    $form[0].submit();
    
}

function js_redirect(href)
{
    if (href.indexOf('http://')!=-1) {
        var location = href;
    }
    else {
        var host = window.location.hostname;
        var location = 'http://' + host + '/' + href;
    }
    
    window.location = location;
    
}


function populate_design_options(category, selected_design)
{
    var options = '';
    $('#search_design').html('');
    for (var i=0; i<design_js_options.length; i++) {
        if (category && category!='all' && i!=0 && design_js_options[i].category!=category) continue;
        options+='<option '+(selected_design == design_js_options[i].name ? " selected='selected' " : "" )+' value="'+design_js_options[i].name+'">'+(design_js_options[i].name)+'</option>';
    }
    $('#search_design').html(options);
}

function populate_park_options(city, selected_park)
{
    var park_options = park_js_options[city];
    if (park_options==undefined) {
        $('#park_options_holder').hide();
        $('#search_park').html('<option value="0" selected="selected">mindegy</option>');
        return;
    }
    else {
        $('#park_options_holder').show();
    }
    var options = '';
    for (var i=0; i<park_options.length; i++) {
        options+='<option '+(selected_park == park_options[i].id ? " selected='selected' " : "" )+' value="'+park_options[i].id+'">'+(park_options[i].name)+'</option>';
    }
    $('#search_park').html(options);
}


function populate_modell_options(brand, selected_modell)
{
    var modell_options = model_js_options[brand];
    if (modell_options==undefined || brand=='0') {
        $('#model_options_holder').hide();
        $('#search_modell').html('<option value="0" selected="selected">mindegy</option>');
        return;
    }
    else {
        $('#model_options_holder').show();
    }
    
    var options = '';
    
    for (var i=0; i<modell_options.length; i++) {
        var class_name = '';
        class_name = modell_options[i].is_parent===1 ? 'parent' : (modell_options[i].is_child===1 ? 'child' : '');
        options+='<option class="'+class_name+'" '+(selected_modell == modell_options[i].id ? " selected='selected' " : "" )+' value="'+modell_options[i].id+'">'+(class_name=='child' ? '&nbsp;&nbsp;&nbsp;' : '')+(modell_options[i].name)+'</option>';
    }
    $('#search_modell').html(options);
    
}

function init_search() {
         
    if ( $('#search_form').length==0 ) return;
    var search_validator = {
        blocks: [{
            block_id: 'search_block',
            fields: {
                temp_search_price_from: {
                    format: 'formatted_digits'
                },
                temp_search_price_to: {
                    format: 'formatted_digits'
                }
            }
        }]
    }
    var search_pform = $('#search_form').pformValidate( search_validator, {}, pform_options ); 
    
    $('[name="search_type"]').bind('change', function(e) {
        if ( search_pform.isValid() ) ajax_count_search_results();
    });

    $('[name="search_category"]').bind('change', function(e) {
        if ( search_pform.isValid() ) ajax_count_search_results();
    });
    
    
    $('#search_gyartmany').bind('change', function(e) {
        populate_modell_options($(this).val(), selected_modell);
    });
    populate_modell_options( $('#search_gyartmany').val(),selected_modell );
    
    
    $('#temp_search_price_from').bind('keyup blur', function(e) {
        var val = $('#temp_search_price_from').val();
        val = val.split(' ').join('');
        $('#search_price_from').val(val);
    });
    
    $('#temp_search_price_to').bind('keyup blur', function(e) {
        var val = $('#temp_search_price_to').val();
        val = val.split(' ').join('');
        $('#search_price_to').val(val);
    });
    
    $('#temp_search_price_from,#temp_search_price_to').bind('keyup', function(e) {
        number_format(e, this);
        if ( search_pform.isValid() ) ajax_count_search_results();
    });
    
    $('[name="search_category"]').bind('change', function(e) {
        if (this.checked==true) populate_design_options(this.value, 0);
    });
    
    populate_design_options( $('[name="search_category"]:checked').val(), selected_design );
    $('#search_button').bind('click', function(e) {
        e.preventDefault();
        if (search_pform.isValid()) {
            $(this).parents('form')[0].submit();
        }
        else {
            alert('Hibás adatok az űrlapon!');
        }
    });
    
    populate_park_options( $('#search_city').val(), selected_park);
    $('#search_city').bind('change', function(e) {
        var val = $(this).val();
        populate_park_options(val, selected_park);
    })
    
    $('#search_form select').bind('change', function(e) {
        if ( search_pform.isValid() ) ajax_count_search_results();
    })
    
}

function step_main_banner()
{
    var $actual_banner = $('#main_banner a:visible');
    var $target_banner = $actual_banner.next();
    if ($target_banner.length==0) {
        $target_banner = $('#main_banner a:first');
    }
    $actual_banner.fadeOut('slow');
    $target_banner.fadeIn('slow');
    
}

function init_main_banner()
{
    $('#main_banner a').not(':first').hide();
    setInterval('step_main_banner()', 5000);
}

function init_box_headers()
{
    $.each($('#pg_boxes .box'), function() {
        var href = $('a:first', this).attr('href');
        $('.box_header', this).bind('click', function(e) {
            js_redirect(href);
        })
    });
}

function make_default_page(el)
{
     if(navigator.userAgent.indexOf('MSIE')!=-1)
     {
          el.style.behavior = 'url(#default#homepage)'; 
          el.setHomePage('http://www.hovany.hu');
     } 
     else 
     {
         alert('Az automatikus beállítást nem támogatja a böngészője.\nKérjük, a böngésző beállításainál állítsa be az oldalt kezdőlapnak.');
     }
}

function popup_gallery(id)
{
    var current_location = window.location.href;
    var id = $('#actual_pic').val();
    if (id==undefined) return false;
    current_location = current_location.replace('#car_video', '');
    
    var new_href = current_location.replace('/auto/', '/galeria/')+'/'+id;
    
    if (current_location.indexOf('/embedd_car/')>0) {
        new_href = current_location.replace('/embedd_car/', '/galeria/')+'/'+id;
    }
    
    var popup_window = window.open(new_href, 'gallery_popup', 'toolbar=0,location=0,status=0,menubar=0,scrollbars=0,resizable=0,width=800,height=620'); 
    if (window.focus) popup_window.focus();
    return false;
    
}

function init_spec_banner()
{
    if (!$('#pg-spec-banner').length) return;
    var banner_file = $('#pg-spec-banner SPAN').html();
    var swfobject_params = {
        wmode: "transparent"
    };
    swfobject.embedSWF(banner_file, "pg-spec-banner", "692", "120", "9.0.0", "", {}, swfobject_params);
}

function toggle_fixed_bottom()
{
    var is_closed = $('#fixed_bottom').hasClass('closed');
    var is_two_rows = $('#fixed_bottom').hasClass('two_rows');
    
    $('#fixed_bottom').animate(
        {'bottom': is_closed ? '0' : is_two_rows ? '-222px' : '-120px' },
        200,
        'linear',
        function() {
            $(this).toggleClass('closed');
            $('.toggle .text', this).html( is_closed ? 'Bezár' : 'Kinyit');
            var cookie_value = is_closed ? 'opened' : 'closed'
            createCookie('fixed_bottom_opened', cookie_value, 10);
        }
    );
    
}

function add_to_compare(kod)
{
    var total = $('#fixed_bottom .car_item').length;
    if (total>=10) {
        alert('A parkolóban egyszerre maximum 10 autó szerepelhet!');
        return false;
    }
    $.ajax({
        url: 'car/ajax_add_to_compare/',
        data: {
            'kod' : kod
        },
        type: 'post',
        success: function(response) {
            get_compared_cars();
        }
    })
}

function remove_from_compare(el, kod)
{
    $item = $(el).parents('.car_item');
    $item.fadeTo(50, 0, function() {
        $.ajax({
            url: 'car/ajax_remove_from_compare/',
            data: {
                'kod' : kod
            },
            type: 'post',
            success: function(response) {
                get_compared_cars();
            }
        })
    });
}

function recommend(kod)
{
    tb_show('Ajánló küldése', 'car/recommend/'+kod+'?TB_iframe=1&width=400&height=300');
}

function send_parking(kod)
{
    tb_show('Parkoló küldése', 'send_parking/?TB_iframe=1&width=400&height=220');
}

function get_compared_cars(init)
{
    if (init==true) {
        var fixed_bottom_opened = readCookie('fixed_bottom_opened');
        if (fixed_bottom_opened=='opened') {
            $('#fixed_bottom').removeClass('closed');
             $('#fixed_bottom .toggle .text').html('Bezár');  
        }
        else {
            $('#fixed_bottom').addClass('closed');
        }
    }
    $.ajax({
        url: 'car/ajax_get_compared_cars/'+Math.floor(Math.random()*100000),
        type: 'get',
        success: function(response) {
            $('#fixed_bottom .ajax_content').html(response);
            var total = $('#fixed_bottom .car_item').length;
            
            if (total>0) {
                $('#fixed_bottom .total').html('('+total+' autó kijelölve) ');
                if ( $('#fixed_bottom').hasClass('closed') && !init) {
                    toggle_fixed_bottom();
                }
                if (total>5) {
                    $('#fixed_bottom').addClass('two_rows');
                }
                else {
                    $('#fixed_bottom').removeClass('two_rows');
                }
            }
            else {
                $('#fixed_bottom .total').html('');
                
                /*
                if ( !$('#fixed_bottom').hasClass('closed') && !init ) {
                    toggle_fixed_bottom();
                }
                */
            }
        }
    })
}

$('document').ready( function() {
    init_search();
    ajax_count_search_results();
    init_main_banner();
    init_box_headers();
    
    if ($('#fixed_bottom').length>0) {
        get_compared_cars(true);
    }
    
    var swfobject_params = {
        wmode: "transparent"
    };
    swfobject.embedSWF("media/flash/logok_780x80.swf", "pg_logo_holder", "780", "80", "9.0.0", "", {}, swfobject_params);
    
    swfobject.embedSWF('media/flash/eurofleet_btn.swf', "button_eurofleet_swf", "229", "83", "9.0.0", "", {}, swfobject_params);
    
    swfobject.embedSWF('media/flash/hovanyalkusz_btn.swf', "button_hovanybiztositas_swf", "229", "83", "9.0.0", "", {}, swfobject_params);
    
    init_spec_banner();
    
    var newsletter_validator = {
        blocks: [{
            block_id: 'newsletter_block',
            fields: {
                 newsletter_name: {
                    required: true
                },
                newsletter_email: {
                    required: true,
                    format: 'email'
                }
            }
        }]
    }
    
    
    
    
    if ($('#newsletter_module_form').length>0) {
        var newsletter_pform = $('#newsletter_module_form').pformValidate( newsletter_validator, {}, pform_options ); 
        $('#newsletter_button').bind('click', function(e) {
            e.preventDefault();
            if (newsletter_pform.isValid()) {
                $(this).parents('form')[0].submit();
            }
            else {
                alert('Hibás adatok az űrlapon!');
            }
        })
    }
    
    $("#pg_main_menu li").hoverIntent(
        function(e) {
            $('ul', this).slideDown('fast').bgiframe();
        },
        function(e) {
            $('ul', this).slideUp('fast');
        }
    )
    
    $('.modal_close').bind('click', function(e) {
        e.preventDefault();
        $.unblockUI();
    })
    
    $('.inner #recent_cars .car_item').bind('click', function(e) {
        var href = $('a', this).attr('href');
        js_redirect(href);
    })
})

