var google_hirdetesek = new Array();
var isFogkefeBanner = false;

$(function(){

    //cikkekbe szúrt jobboldali kis képekre cromeban való szöveg ráúszás javítása
    $('.cikkTableright').wrap('<div stlye="float: right; clear: right; width: 304px;" />');
    
    /*$('#pMenu div').hover(
        function(){
            $(this).addClass("hovered")
        },
        function(){
            $(this).removeClass("hovered")
        }
    )*/
    $(".scrollable").scrollable();

    $('.listBrowserTab').show().hide();
    var listBrowserTab = new TABCONTROL('listBrowser', {});
    listBrowserTab.init();
    
    
    var serviceBoxButtonsTab = new TABCONTROL('serviceBoxButtons', {});
    serviceBoxButtonsTab.init();
    
    var searchServiceBoxButtonsTab = new TABCONTROL('searchServiceBoxButtons', {});
    searchServiceBoxButtonsTab.init();
    
    var multimediaSwitcher = new TABCONTROL('multimediaSwitcher', {});
    multimediaSwitcher.init();
    

    var f1CsapatEredmenyekBox = new TABCONTROL('f1CsapatEredmenyekBox', {});
    f1CsapatEredmenyekBox.init();

    var f1Eredmenyek = new TABCONTROL('f1Eredmenyek', {});
    f1Eredmenyek.init();

    var f1KonstuktoriEredmenyek = new TABCONTROL('f1KonstuktoriEredmenyek', {});
    f1KonstuktoriEredmenyek.init();

    var f1NagydijakAdatai = new TABCONTROL('f1NagydijakAdatai', {"opendfirst":false,"nojstab":true});
    f1NagydijakAdatai.init();

    var f1PalyaEredmenyek = new TABCONTROL('f1PalyaEredmenyek', {});
    f1PalyaEredmenyek.init();

    var pMainContainerOffset = $('#leftColContentContainer').offset();


    //minden adattábla utolsó sora kap egy classt
    $('table.dataTable').find('tr:last').addClass('last');


});

function number_format(number, decimals, dec_point, thousands_sep) {
    // Formats a number with grouped thousands
    //
    // version: 1004.2314
    // discuss at: http://phpjs.org/functions/number_format
    var n = !isFinite(+number) ? 0 : +number,
        prec = !isFinite(+decimals) ? 0 : Math.abs(decimals),
        sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep,        dec = (typeof dec_point === 'undefined') ? '.' : dec_point,
        s = '',
        toFixedFix = function (n, prec) {
            var k = Math.pow(10, prec);
            return '' + Math.round(n * k) / k;};
    // Fix for IE parseFloat(0.55).toFixed(0) = 0;
    s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.');
    if (s[0].length > 3) {
        s[0] = s[0].replace(/\B(?=(?:\d{3})+(?!\d))/g, sep);}
    if ((s[1] || '').length < prec) {
        s[1] = s[1] || '';
        s[1] += new Array(prec - s[1].length + 1).join('0');
    }return s.join(dec);
}

function ucfirst (str) {
    // Makes a string's first character uppercase
    //
    // version: 1004.2314
    // discuss at: http://phpjs.org/functions/ucfirst    
    var f = str.charAt(0).toUpperCase();
    return f + str.substr(1);
}

var Vezess = {Info: {}};
Vezess.Info.Monts = {
    1: 'január',
    2: 'február',
    3: 'március',
    4: 'április',
    5: 'május',
    6: 'június',
    7: 'július',
    8: 'augusztus',
    9: 'szeptember',
    10: 'október',
    11: 'november',
    12: 'december'
};

/**
 * A katalogus keresőhöz a működés
 */
var KatalogSeatch = function(oConfig){
    var self = this;
    var oConf = oConfig;
    oConf.originalValues = oConf.values;
    var oScope;

    this.init = function( oScopeObj, defSliderValues ){
        oScope = oScopeObj;

        this.initMarka();
        this.initTipus();
        this.initSlider( defSliderValues );
    }

    function mod( a ){
        return oConf.values[a];
    }

    function updateSlide(event, ui) {
        $(".ar_tol", oScope).val( mod(ui.values[0])*1000000);
        $(".ar_ig", oScope).val( mod(ui.values[1])*1000000 );
        $(".amount", oScope).html(
            [ mod(ui.values[0]), ' és ', mod(ui.values[1]), ' MFt között' ].join('')
        );
    }

    this.initMarka = function(){
        
        $('.jsKatalogusMarka', oScope).live('change', function(){
            $('.jsKatalogusTipus, .jsKatalogusDinamic', oScope )
                .html('<option />')
                .attr('disabled', 'disabled');

            $.ajax({
                url: oConf.api,
                type: 'POST',
                data: {
                    'action':'getTipus',
                    'marka':$(this).val(),
                    'uj_auto': oConf.ujAuto
                },
                success: function( html ){
                    $('.jsKatalogusTipus', oScope)
                        .html( html )
                        .removeAttr('disabled');
                }
            });
            var val = $(this).val();
            if (KatalogSeatch.prices[val]) {
                var newValues = [];
                var minp = parseInt(KatalogSeatch.prices[val].min_price);
                var maxp = parseInt(KatalogSeatch.prices[val].max_price);
                for (var i = 0; i <= 20; i++) {
                    newValues[i] = ((minp + (maxp - minp)*i/20) / 1000000).toFixed(1);
                }
                oConf.values = newValues;
            } else {
                oConf.values = oConf.originalValues;
            }
            $('div.slider-range').slider('values', [0, 20]);
            updateSlide(null, {values: [0, 20]});
        });

    }

    this.initTipus = function(){
        $('.jsKatalogusTipus', oScope).live('change', function(){
            $.ajax({
                url: oConf.api,
                type: 'POST',
                data: {
                    'action':'getTipusPrice',
                    'marka':$('.jsKatalogusMarka', oScope).val(),
                    'tipus': $(this).val()
                },
                success: function(result) {
                    var data = $.parseJSON(result);

                    var minp = parseInt(data.min_price);
                    var maxp = parseInt(data.max_price);

                    if (isNaN(minp))
                        minp = 0;
                    if (isNaN(maxp))
                        maxp = 0;

                    var newValues = [];
                    for (var i = 0; i <= 20; i++) {
                        newValues[i] = ((minp + (maxp - minp)*i/20) / 1000000).toFixed(1);
                    }
                    oConf.values = newValues;
                    updateSlide(null, {values: $('div.slider-range').slider('values')});
                }
            });

            $.post( oConf.api,
                {
                    'action': 'get' + ucfirst( $('.jsKatalogusDinamic', oScope).attr('name') ),
                    'tipus':$(this).val(),
                    'marka': $('.jsKatalogusMarka', oScope).val(),
                    'uj_auto': oConf.ujAuto
                },
                function( html ){
                    $('.jsKatalogusDinamic', oScope)
                        .html( html )
                        .removeAttr('disabled');
                }
            );
        });
    }

    this.initSlider = function( defSliderValues ){
        var oSlider = $(".slider-range", oScope);
        if( oSlider.size() != 1 ) return;
        
        oSlider.slider({
            range: true,
            min: 0,
            max: 20,
            values: defSliderValues || [0,10],
            slide: updateSlide
        })
        .slider('option', 'slide')({}, {values: defSliderValues? defSliderValues: oSlider.slider('option', 'values')});
    }


}

/**
 * Új autos extrak ajanlatkereshez
 */
var ExtrakAjanlat = new function(){
    var self = this;

    this.init = function(){

        //checkboxok kalkuláció
        $('#extrakList input:checkbox').bind('change', self.doCalc );

        //form megjelenítés
        $('#jsAjanlatotKerekBtn').bind('click', function(){
            $('#extrakListForm').toggle();
            $(this).toggle();
        });

        //form validáció
        $('#extrakBox form').bind('submit', self.doSubmit );
    }

    this.doCalc = function(){

        self.updateSum(
            $(this).parents('tr').find('.priceCol h6').text(), //price
            $(this).attr('checked')? 1:-1 //modify
        );
    }

    this.updateSum = function( sPrice, iModify){

        var oSum = $('#extrakListSum .extraFullPrice');
        var iPrice = this.toInt( oSum.text() );

        iPrice += this.toInt( sPrice ) * iModify;
        oSum.text( this.formatPrice( iPrice ) );
    }

    this.toInt = function( sInt ){
        return parseInt( (sInt||'').replace(/[^0-9]/gi, '' ) );
    }

    this.formatPrice = function( iPrice ){
        return number_format( iPrice, ' ', ' ', ' ' ) + ' Ft';
    }

    this.doSubmit = function(){

        if( self.doValidate( $(this) ) != true ){
            return false;
        }
        $(this).submit();

        return true;
    }


    this.doValidate = function( oForm ){

        oForm.find('.error').hide();

        //TODO: formátum ellenőrzés
        if(
            $.trim( oForm.find("input[name='ajanlat_email']").val() ) == '' &&
            $.trim( oForm.find("input[name='ajanlat_phone']").val() ) == ''
        ){
            oForm.find('.error').show();
            return false;
        }

        return true;
    }


}


var CikkKereso = function( scope ){
    var self = this;
    var oScope = scope || document;
    var oConfig;

    this.init = function( conf ){
       oConfig = conf || {};

       this.initSlider();

    }

     this.initSlider = function(){

        var oSlider = $(".date-range", oScope);
        if( oSlider.size() != 1 ) return;

        oSlider.slider({
            range: true,
            min: 0,
            max: oConfig.dateItems.length-1,
            values: [0,  oConfig.dateItems.length-1],
            slide: function(event, ui) {

                $(".date-text", oScope).html(
                    self.formatDate( oConfig.dateItems[ui.values[0]] )
                    +' - '+
                    self.formatDate( oConfig.dateItems[ui.values[1]] )
                );
                    
                $('.datum_tol', oScope).val( oConfig.dateItems[ui.values[0]] );
                $('.datum_ig', oScope).val( oConfig.dateItems[ui.values[1]] );
            }
        });
        oSlider.slider('values', oConfig.values || oSlider.slider('option', 'values') );
        //a trigger valamiért nem működik :( - szicsu
        oSlider.slider('option', 'slide')({}, {values: oSlider.slider('option', 'values')});
    }

    this.formatDate = function( sDate ){

        var aSegment = sDate.split('-');
        return aSegment[0] +' '+ Vezess.Info.Monts[ parseInt( aSegment[1] ) ];
    }

}


var MultimediaKereso = function( scope ){
    var self = this;
    var oScope = scope || document;

    this.init = function(){

        //pager gombok
        $('#multimediaKeresoAjaxResultContainer .pager a', oScope).live('click',function(){
             self.doLoad($(this).attr('href') );
             return false;
        });

        //form és indiítás
        $('#multimediaKereso', oScope).bind('submit',function(){
            self.doLoad(
                $(this).attr('action'),
                $(this).serialize()
            );
            return false;
        }).trigger('submit');

    }

    this.loadGallery = function(e) {
        e.preventDefault();
        $.get('/ajax/gallery',
            {cikkurl: $(this).attr('href')},
            function(html) {
                $('#multimediaKeresoAjaxResultContainer').html(html)
            }
        );
    }

    this.doLoad = function( url, data ){
        $.get( url, data || {}, function( html ){
            $('#multimediaKeresoAjaxResultContainer', oScope)
                .html( html )
                .find('.pager').addClass('multimediaPager');
            $('#multimediaKeresoAjaxResultContainer a', oScope).click(self.loadGallery);
        });
    }

}

/**
 * A tesztkereső
 */
var TesztSearch = function( scope ){
    var self = this;
    var oScope = scope || document;
    var oConf = {};

    this.init = function( conf ){
        oConf = conf || {};

        this.initMarka();
        this.initForm();
    }

    this.initMarka = function(){

        $('.jsTesztMarka', oScope).live('change', function(){
            $('.jsTesztTipus', oScope )
                .html('<option />')
                .attr('disabled', 'disabled');

            $.ajax({
                url: oConf.api,
                type: 'POST',
                data: {
                    'action':'getTipus',
                    'marka':$(this).val()
                },
                success: function( html ){
                    $('.jsTesztTipus', oScope)
                        .html( html )
                        .removeAttr('disabled');
                }
            });
        });

    }


    this.initForm = function(){
        $('.jsTesztForm', oScope).bind('submit',function(){
            /*
            $(this).find("input[name='szo']").val(
                    $.trim( [$('.jsTesztMarka', oScope).val(), $('.jsTesztTipus', oScope).val()].join(' ') )
                );
              */
            var aKcsat = [];
            $(this).find("input[name='csatorna']").filter(':checked').each(function(){
                aKcsat.push( $(this).val() );
            });
            if( aKcsat.length > 0 ){
               $(this).find("input[name='kcsat']").val( aKcsat.join(',') );
            }
            $(this).submit();
           return false;
        });
    }
    
}


/* NYITÓ OLDALI BANNER */
jQuery.fn.nyitobanner = function() {
    if (arguments.length == 0) {
        $('img', this).hover(jQuery.nyitobanner.hoverElement);
        $(this).mouseout(jQuery.nyitobanner.mouseOutContainer)
    } else if (arguments[0] == 'large') {
        jQuery.nyitobanner.makeLarge(this);
    }

    var p = $('#nyitoBanner').offset()

    $('#nyitoBanner img').css('top', '68px').css('display', 'block') //p.top - 234
	//120
};

jQuery.nyitobanner = {
    getLeftDelta: function (el) {
        if (el.is('.elso')) {
            return 0;
        } else if (el.is('.masodik')) {
            return 52;
        } else if (el.is('.harmadik')) {
            return 104;
        }
    },

    removeLargeness: function (el, elLarge) {
        jQuery.nyitobanner.animating = true;
        var leftDelta = '+=' + jQuery.nyitobanner.getLeftDelta(el);

        var p = $('#nyitoBanner').offset()

        el.animate({
            top: '68px', //top: (p.top - 234), //120
            height: 147,
            width: 196,
            left: leftDelta
        }, {
            specialEasing: {
                top: 'easeOutBack',
                height: 'easeOutBack',
                left: 'easeOutBack'
            },
            complete: function() {
                $(this).css('z-index', 0);
                jQuery.nyitobanner.addLargeness(elLarge);
            }
        }).removeClass('nagy');

    },

    addLargeness: function (el) {
        jQuery.nyitobanner.animating = true;
        el.css('z-index', 2);
        var leftDelta = '-=' + jQuery.nyitobanner.getLeftDelta(el);
        var p = $('#nyitoBanner').offset()

        el.animate({
            top: '48px', // top: (p.top - 264), //140
            height: 223,
            width: 297,
            left: leftDelta
        }, {
            specialEasing: {
                top: 'easeInOutQuart',
                height: 'easeInOutQuart',
                left: 'easeInOutQuart'
            },
            complete: function() {
                jQuery.nyitobanner.animating = false;
            }
        }).addClass('nagy');
    },

    makeLarge: function(el) {
        el = $(el);
        if (el.is('.nagy')) return;
        if (el.parent().parent().find('.nagy').length == 0) {
            jQuery.nyitobanner.addLargeness(el);
        } else {
            jQuery.nyitobanner.removeLargeness(el.parent().parent().find('.nagy'), el);
        }
    },

    hoverElement: function () {
        jQuery.nyitobanner.startTimer(this);

    },

    mouseOutContainer: function() {
        //jQuery.nyitobanner.startTimer($('.masodik', this));
        jQuery.nyitobanner.clearTimer();
    },

    startTimer: function(el) {
        jQuery.nyitobanner.clearTimer();
        jQuery.nyitobanner.timer = setTimeout(function() {
            jQuery.nyitobanner.makeLarge(el);
        }, jQuery.nyitobanner.animating ? 800 : 200);

    },

    clearTimer: function() {
        if (jQuery.nyitobanner.timer) {
            clearTimeout(jQuery.nyitobanner.timer);
            jQuery.nyitobanner.timer = null;
        }
    }

}

/* GALÉRIA */
function aScrollLeft(aObj) {
    new_frame_no = ((frame_no/1)-1);
    new_left = ((frame_left/1) + move_by);
    new_left_attr = new_left+"px";
    if(new_frame_no > 0) {
        $('#gallery_tns').css({left: new_left_attr});
        frame_left = new_left;
        frame_no = new_frame_no;
    }
    $(aObj).trigger('blur');
}

function aScrollRight(aObj) {
    new_frame_no = ((frame_no/1)+1);
    new_left = ((frame_left/1) - move_by);
    new_left_attr = new_left+"px";
    if(new_frame_no < max_clicks) {
        $('#gallery_tns').css({left: new_left_attr});
        frame_left = new_left;
        frame_no = new_frame_no;
    }
    $(aObj).trigger('blur');
}

function galeriaSwitchTo(pic, lbId, aObj) {
    $('a.selected').removeClass('selected');
    $(aObj).addClass('selected').trigger('blur');
    var altText = $('img', aObj).attr('alt');

    w = $('img', aObj).attr('sx');
    h = $('img', aObj).attr('sy');
    if (w && h) {
        var rTarget = 550/318;
        if (w / h > rTarget) {
            $('#gallery_pic img').attr('width', 550).removeAttr('height');
        } else {
            $('#gallery_pic img').attr('height', 318).removeAttr('width');
        }
    }
    var gal = $(aObj).parents('#gallery:first')[0];
    $('#gallery_pic img:first',gal).attr("src", pic+galleryPostfix);
    if (altText) {
        $('#gallery_pic img:first',gal).attr('alt', altText).attr('title', altText);
        $('#gallery_text:first',gal).text(altText);
    }
    bigPic = pic;
    lightboxId = lbId;
}

function initGalleryScroller() {
    var timer = null;

    $('#gallery_pic img, #gallery_button1_large, #gallery_button2_large').hover(function() {
        $('#gallery_button1_large, #gallery_button2_large').show();
        if (timer) {
            clearTimeout(timer);
            timer = null;
        }
    }, function() {
        if (! timer) {
            timer = setTimeout(function() {
                $('#gallery_button1_large, #gallery_button2_large').hide();
            }, 50);
        }
    });

    $('#gallery_pic img').click(function(e) {
        if (e.pageX < $(this).offset().left + $(this).width()/2) {
            $('#gallery_tns_container a.selected').prev().click();
        } else {
            $('#gallery_tns_container a.selected').next().click();
        }
    });

    var altText = $('#gallery_pic img').attr('alt');
    $('#gallery_text').text(altText);

}

function clickLightbox(href) {
    $('a[href$="'+href+'"]').click();
}

function reloadAndJump(anchor) {
    location.href=location.href.split(/\?|#/)[0] + '#' + anchor;
    location.reload(true);
    return false;
}

function google_ad_request_done(google_ads) {
    var i=0;
    $('div.szponzoraltHirdetesBox.empty').each(function() {
        $(this).children('div.vezessGoogleBox').html(function() {
            var s = '';
            for (var j=0; j<$(this).attr('adcount'); j++) {
                if (j==$(this).attr('adcount')-1) boxClass = 'lastContainer';
                else boxClass = '';
                if (google_ads[i] != undefined) {
                    s += '<br><div class="googleAdContainer '+boxClass+'"><a href="' + google_ads[i].url + '" ' +
                         'onmouseout="window.status=\'\'" ' +
                         'onmouseover="window.status=\'go to ' +
                         google_ads[i].visible_url + '\';return true;" ' +
                         'class="">' +
                         '<br><span>' +
                         '<h2 class="articleTitle">' + google_ads[i].line1 + '</h2><br></span></a>' + 
                         '<span style="color:#292929">' +
                         google_ads[i].line2 +
                         google_ads[i].line3 + '<br></span>' +
                         '<a href="' + google_ads[i].url + '" ' +
                         'onmouseout="window.status=\'\'" ' +
                         'onmouseover="window.status=\'go to ' +
                         google_ads[i].visible_url + '\';return true;" ' +
                         'class="">' +
                         '<span>' +
                         google_ads[i].visible_url + '</span></a></div><br>';
                }
                i++;
            }
            return s;
            
        });
        $(this).removeClass('empty');
    });
}

function searchCheck() {
	if($('#searchQuery').val().length < 3) {
		window.alert("A keresőszónak legalább 3 karakteresnek kell lennie.");
		return false;
	}
}

function cikkNagyKeresoCheck() {
	if($('#cikkNagyKeresoPSearch').val().length < 3) {
		window.alert("A keresőszónak legalább 3 karakteresnek kell lennie.");
		return false;
	}
}

function positionOuterBox() {
	if(isFogkefeBanner && window.location.pathname != '/regisztracio/') {
		var pContentHeight = parseInt($('#pContent').css('height'));
		$('#pContent').css('height', (pContentHeight - containerTop) + 'px');
	}
}

//gyorskereső pozicionálás
function f_filterResults(n_win, n_docel, n_body) {
    var n_result = n_win ? n_win : 0;
    if (n_docel && (!n_result || (n_result > n_docel)))
        n_result = n_docel;
    return n_body && (!n_result || (n_result > n_body)) ? n_body : n_result;
}
function f_scrollTop() {
    return f_filterResults (
        window.pageYOffset ? window.pageYOffset : 0,
        document.documentElement ? document.documentElement.scrollTop : 0,
        document.body ? document.body.scrollTop : 0
    );
}
function f_clientHeight() {
    return f_filterResults (
        window.innerHeight ? window.innerHeight : 0,
        document.documentElement ? document.documentElement.clientHeight : 0,
        document.body ? document.body.clientHeight : 0
    );
}

function setQuickSearchPosition(){
    $('#gyorskeresoContainer').css('top', (f_clientHeight()-parseInt($('#gyorskeresoContainer').height()))+'px');
    $('#gyorskeresoAlatet').css('top', (f_clientHeight()-parseInt($('#gyorskeresoAlatet').height()))+'px');
}

function setQuickSearchCloseButtonPosition(posIE, posElse){
    if($.browser.msie){
        $('#gyorskeresoClose').css({
            position: 'relative',
            top: posIE+'px'
        })
    }else{
        $('#gyorskeresoClose').css({
            position: 'relative',
            top: posElse+'px'
        })
    }
}

