var ie6=(jQuery.browser.msie && jQuery.browser.version.substr(0,1)<7);

(function($){
    if (typeof $.parseJSON !== 'function') {
        // JSON RegExp
        var rvalidchars = /^[\],:{}\s]*$/, 
            rvalidescape = /\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, 
            rvalidtokens = /"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, 
            rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g;
        
        $.extend({
            parseJSON: function(data){
                if (typeof data !== "string" || !data) {
                    return null;
                }
                
                // Make sure leading/trailing whitespace is removed (IE can't handle it)
                data = jQuery.trim(data);
                
                // Make sure the incoming data is actual JSON
                // Logic borrowed from http://json.org/json2.js
                if (rvalidchars.test(data.replace(rvalidescape, "@").replace(rvalidtokens, "]").replace(rvalidbraces, ""))) {
                
                    // Try to use the native JSON parser first
                    return window.JSON && window.JSON.parse ? window.JSON.parse(data) : (new Function("return " + data))();
                    
                }
                else {
                    jQuery.error("Invalid JSON: " + data);
                }
            }
        });
    }
})(jQuery);

function karacsonyFlashPromo() {
    if ($("promoFlashContainer")) {
        var flash = new SWFObject("/static/swf/karacsonyi-nyito2009.swf", "karacsonyi-nyito2009", "734", "348", "9", "#ffffff");
        flash.addParam("wmode", "opaque"); 
        flash.write('promoFlashContainer'); 
    }
}

Event.observe( window, 'load', function() {
    karacsonyFlashPromo()
});

/* world class roaming tarifak lenyilo tooltip start */
function toolTipShow(element) {
    var isVisible = $(element).next('div.toolTipDropDown').style.display;
    if (isVisible == 'block') {
        $(element).next('div.toolTipDropDown').style.display = 'none';
    }
    else if (isVisible == 'none') {
        $(element).next('div.toolTipDropDown').style.display = 'block';
    }
    return false;
}

function toolTipHide(element) {
    $(element).up("div.toolTipDropDown").style.display = "none";
}

/* world class roaming tarifak lenyilo tooltip end */


/* cookie a tabos pager statusz megjegyzesehez start */

var tCookie = Class.create();
Object.extend(tCookie.prototype, {

    initialize: function() {
    },

    set: function(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=/";
    },

    get: function(name) {
        var nameEQ = name + "=";
        var retVal = null;
        var cookies = document.cookie.split(';');
        cookies.each(function(cookieItem){
            while (cookieItem.charAt(0)==' ') cookieItem = cookieItem.substring(1,cookieItem.length);
            if (cookieItem.indexOf(nameEQ) == 0) retVal = cookieItem.substring(nameEQ.length,cookieItem.length);
        });
        return retVal;
    },

    erase: function(name) {
        this.set(name,"",-1);
    }
});

var Cookie = new tCookie();

/* cookie a tabos pager statusz megjegyzesehez end */

/* tabos pager start */

tabbedPagerClass = Class.create();
tabbedPagerClass.prototype = {
    initialize : function(_tabbedPanelsContent, _itemContainerClass, _itemClass, _visibleNewsItemsPerPage, _tabsCookieId) {
        this.visibleNewsItemsPerPage = _visibleNewsItemsPerPage;
        this.tabbedPanelsContent = _tabbedPanelsContent;
        this.newsItems = $(this.tabbedPanelsContent).down('div.' + _itemContainerClass).select('div.' + _itemClass);
        this.pageNum = Math.ceil(this.newsItems.length / this.visibleNewsItemsPerPage);
        this.pagers = $(this.tabbedPanelsContent).select('div.navigation');
        this.buildPager();
        this.setEvents();
        this.tabsCookieId = _tabsCookieId;
        if (Cookie.get(this.tabsCookieId)) {
            this.cookieValue = Cookie.get(this.tabsCookieId).split(',')
        }
        else {
            this.cookieValue = new Array(0, 0);
        }
        this.showPage();
        this.actualPage = 1;
    },
    countNewsItems : function () {
        return $(this.tabbedPanelsContent).down('div.' + _itemContainerClass).select('div.' + _itemClass).length;
    },
    setPageNumDisplay : function () {
        for (var i = 0; i < this.pagers.length; i++) {
            $(this.pagers[i]).previous('div.pages').down('span.current').update(this.actualPage + '. oldal');
        }
    },
    setClassNames : function(clickedElement, direction) {
        //a pagerek css osztalyait valtogatjuk iranynak es annak megfeleloen, hogy a lapozas nyilakkal vagy szamra kattintassal tortent
        switch(direction) {
            case 'previous':
                for (var i = 0; i < this.pagers.length; i++) {
                    this.pagers[i].down('li.current').removeClassName('current');
                    this.pagers[i].down('li.prevPage').removeClassName('inactive');
                    this.pagers[i].down('li.nextPage').removeClassName('inactive');
                    this.pagers[i].down('li', this.actualPage).addClassName('current');
                }
                if (this.actualPage == 1) {
                    for (var i = 0; i < this.pagers.length; i++) {
                        this.pagers[i].down('li.prevPage').addClassName('inactive');
                    }
                }
                if (this.actualPage > 1) {
                    for (var i = 0; i < this.pagers.length; i++) {
                        this.pagers[i].down('li.nextPage').removeClassName('inactive');
                    }
                }
                break;
            case 'next':
                for (var i = 0; i < this.pagers.length; i++) {
                    this.pagers[i].down('li.current').removeClassName('current');
                    this.pagers[i].down('li.prevPage').removeClassName('inactive');
                    this.pagers[i].down('li.nextPage').removeClassName('inactive');
                    this.pagers[i].down('li', this.actualPage).addClassName('current');
                }
                
                if (this.actualPage == this.pageNum) {
                    for (var i = 0; i < this.pagers.length; i++) {
                        this.pagers[i].down('li.nextPage').addClassName('inactive');
                    }
                }
                if (this.actualPage < this.pageNum) {
                    for (var i = 0; i < this.pagers.length; i++) {
                        this.pagers[i].down('li.prevPage').removeClassName('inactive');
                    }
                }
                break;
            default:
                for (var i = 0; i < this.pagers.length; i++) {
                    this.pagers[i].down('li.current').removeClassName('current');
                    this.pagers[i].down('li.prevPage').removeClassName('inactive');
                    this.pagers[i].down('li.nextPage').removeClassName('inactive');
                    this.pagers[i].down('li', this.actualPage).addClassName('current');
                }
                if (this.actualPage == 1) {
                    for (var i = 0; i < this.pagers.length; i++) {
                        this.pagers[i].down('li.prevPage').addClassName('inactive');
                    }
                }
                if (this.actualPage == this.pageNum) {
                    for (var i = 0; i < this.pagers.length; i++) {
                        this.pagers[i].down('li.nextPage').addClassName('inactive');
                    }
                }
                break;
        }
    },
    onClick : function (e) {
        var clickedElement = $(e.target);

        //hatra lapozunk
        if (!clickedElement.up('li').hasClassName('inactive') && clickedElement.up('li').hasClassName('prevPage')) {
            this.actualPage--;
            this.showPage(this.actualPage, 'previous');
            this.setClassNames(clickedElement, 'previous');
        }
        //elore lapozunk
        else if (!clickedElement.up('li').hasClassName('inactive') && clickedElement.up('li').hasClassName('nextPage')) {
            this.actualPage++;
            this.showPage(this.actualPage, 'next');
            this.setClassNames(clickedElement, 'next');
        }
        //nem lapozunk
        else if (clickedElement.up('li').hasClassName('current') || clickedElement.up('li').hasClassName('inactive')) {
            //do nothing
        }
        //szam alapjan lapozunk
        else {
            this.actualPage = clickedElement.innerHTML;
            this.showPage(this.actualPage, 'direct');
            this.setClassNames(clickedElement, null);
        }
        
        this.setPageNumDisplay();
        
        Event.stop(e);
        return false;
    },
    setEvents : function () {
        //kigyujtjuk a felepitett navigacios elemeket
        var navigationItems = [];
        for (var i = 0; i < this.pagers.length; i++) {
            navigationItems[i] = this.pagers[i].down('ul').select('li');
        }
        
        //rajukkotjuk az esemenyt
        for (var i = 0; i < navigationItems.length; i++) {
            for (var j = 0; j < navigationItems[i].length; j++) {
                Event.observe( navigationItems[i][j].down('a'), 'click', this.onClick.bindAsEventListener(this) );
            }
        }
    },
    buildPager : function () {
        //visszafele lapozo, inaktiv allapotban inicializalva
        for (var i = 0; i < this.pagers.length; i++) {
            $(this.pagers[i]).down('ul').insert('<li class="inactive prevPage"><a href="#">&laquo;</a></li>');
        }

        //oldalszamok inicializalasa, 1-es aktivnak jelolese
        for (var i = 0; i < this.pagers.length; i++) {
            for (var j = 1; j <= this.pageNum; j++) {
                if (j == 1) {
                    $(this.pagers[i]).down('ul').insert('<li class="current"><a href="#">' + j + '</a></li>');
                    continue;
                }
                $(this.pagers[i]).down('ul').insert('<li><a href="#">' + j + '</a></li>');
            }
        }

        //elore lapozo, oldalszamtol fuggo allapotban inicializalva
        if (this.pageNum > 1) {
            for (var i = 0; i < this.pagers.length; i++) {
                $(this.pagers[i]).down('ul').insert('<li class="nextPage"><a href="#">&raquo;</a></li>');
            }
        }
        else {
            for (var i = 0; i < this.pagers.length; i++) {
                $(this.pagers[i]).down('ul').insert('<li class="inactive nextPage"><a href="#">&raquo;</a></li>');
            }
        }
        
        // oldalszamindikatorok inicializalva
        for (var i = 0; i < this.pagers.length; i++) {
            $(this.pagers[i]).previous('div.pages').insert('<strong><span class="current">1. oldal</span>&nbsp;/&nbsp;' +  this.pageNum + '. oldal</strong>')
        }
    },
    showPage : function(pageIndicator, direction) {
        // betoltjuk az elso oldalt
        if (!pageIndicator && !direction) {
            for (var i = 0; i <= this.visibleNewsItemsPerPage - 1; i++) {
                if (i >= this.newsItems.length) {
                    break;
                }
                this.newsItems[i].show();
            }
            if (this.visibleNewsItemsPerPage - 1 <= this.newsItems.length) {
                this.newsItems[this.visibleNewsItemsPerPage - 1].addClassName('last');
            }
            else {
                this.newsItems[this.newsItems.length - 1].addClassName('last');
            }
        }
        else {
            //osszes elrejtese az eddig latszodo utolso elemig
            for (var i = 0; i < this.newsItems.length; i++) {
                this.newsItems[i].hide();
            }

            var newsItemsFromShow = (pageIndicator - 1) * this.visibleNewsItemsPerPage;
            var newsItemsTillShow = (pageIndicator) * this.visibleNewsItemsPerPage;

            for (var i = newsItemsFromShow; i < newsItemsTillShow; i++) {
                if (i == this.newsItems.length) {
                    break;
                }
                if (i == newsItemsTillShow - 1) {
                    this.newsItems[i].addClassName('last')
                }
                this.newsItems[i].show();
            }
            Cookie.set(this.tabsCookieId, Cookie.get(this.tabsCookieId).split(',')[0] + ',' + pageIndicator, '')
        }
    }
};

function initializeTabsPager (visibleNewsItemsPerPage, itemContainerClass, itemClass, tabObject) {
    var tabs = $('tabsArchive').select('div.TabbedPanelsContent');
    var tabsCookieId = 'tabs_' + document.location.href;
    
    var tabbedPagerObjects = [];
    for (i = 0; i < tabs.length; i++) {
        tabbedPagerObjects[i] = new tabbedPagerClass(tabs[i], itemContainerClass, itemClass, visibleNewsItemsPerPage, tabsCookieId);
    }

    if (!(Cookie.get(tabsCookieId))) {
        Cookie.set(tabsCookieId, 0 + ',' + '1', '');
    }
    else {
        var tabStatus = Cookie.get(tabsCookieId).split(',');
        setTabPanels(tabObject, parseInt(tabStatus[0]));
        tabbedPagerObjects[parseInt(tabStatus[0])].actualPage = parseInt(tabStatus[1]);
        tabbedPagerObjects[parseInt(tabStatus[0])].showPage(parseInt(tabStatus[1]));
        tabbedPagerObjects[parseInt(tabStatus[0])].setClassNames(null, null);
        tabbedPagerObjects[parseInt(tabStatus[0])].setPageNumDisplay();
    }
    setYearTabClick(tabsCookieId);
}

function setYearTabClick (tabsCookieId) {
    var tabHeaders = ($('tabsArchive').down('.TabbedPanelsTabGroup')).select('a');
    tabHeaders.each(function (element, index) {
        $(element).observe('click', function(e) {
            Cookie.set(tabsCookieId, index + ',' + '1', '');
        });
    });
}

function setTabPanels(tabObject, num){
    tabObject.showPanel(num);
}
/* tabos pager end */

/**
 * 
 * promoPicBorder magasságának beállítása (onloadra indul)
 * @param -
 * reqiures:  -
*/
function setPromoPicBorder() {
    var promoPicCont=$$('.promoPicCont');
    promoPicCont.each(function(element,index){
            if (element.down('img') && element.down('div.promoPicBorder')) {
                element.down('div.promoPicBorder').style.height=element.down('img').height+'px';
            }
            else if (element.down('img') && element.down('a.promoPicBorder')) {
                element.down('a.promoPicBorder').style.height=element.down('img').height+'px';
            }
    });
}
Event.observe(window,'load',setPromoPicBorder);

/**
 * 
 * magenta keretu tabos lapozo (meg kell hivni a html-bol)
 * @param id a kontener id-ja
 * reqiures:  -
*/

function setMagentaTabs(id) {
    var container = $(id);
    var tabs = container.down('ul.tabContainer').select('li');
    var contents = container.select('div.magentaTabContent');
    tabs.each(function(element, index) {
        Event.observe($(element), 'click', function(e) {
            if ($(element).hasClassName('activeMagentaTab')) {
                Event.stop(e);
                return false;
            }
            else {
                //aktiv tab jeloles
                container.down('li.activeMagentaTab').removeClassName('activeMagentaTab');
                $(element).addClassName('activeMagentaTab');
                //elozo tab borderenek allitasa
                if (container.select('a.greyBorder').length > 1) {
                    container.select('a.greyBorder')[0].removeClassName('greyBorder');
                }
                if (index != 0) {
                    tabs[index - 1].down('a').addClassName('greyBorder');
                }
                //aktiv tartalom megjelenites
                container.down('div.activeMagentaTabContent').removeClassName('activeMagentaTabContent').hide();
                $(contents[index]).addClassName('activeMagentaTabContent').show();
                Event.stop(e);
                return false;
            }
        });
    });
}

Event.observe(window, 'load', function() {
    var tooltipOpeners = $$('a.tooltipOpener');
    for (var i = 0; i < tooltipOpeners.length; i++) {
        Event.observe(tooltipOpeners[i], 'click', function(e){
            var tooltipBox=$(this).next() || $(this).up().next();
            if ($(tooltipBox).style.display == 'none') {
                $(tooltipBox).show();
            }
            else {
                $(tooltipBox).hide();
            }
            
            Event.observe($(tooltipBox.down('a.close')), 'click', function(e) {
               $(tooltipBox).hide();
               Event.stop(e);
            });
            
            Event.stop(e);
        });
    }
    
});

/* jQuery ACCORDION begin */

function accordion(obj, gn){
    this.item = obj;
    this.body = this.item.find('.accordionBody').eq(0);
    this.groupNum = gn || null;
    this.titleContainer = this.item.find('.accordionTitle').eq(0);
    this.closedTitle = this.titleContainer.children().eq(0);
    this.openedTitle = this.closedTitle.next('.openTitle');
    this.bodyHeight = this.body.height();
    this.duration = 500;
}

accordion.prototype = {
    init: function(){
        var self = this;
        this.switchTitle();
        if (!this.titleContainer.hasClass('opened')) {
            this.body.css({
                height: 0,
                opacity: 0
            });
        }
        this.titleContainer.hover(function(){
            jQuery(this).addClass('over');
        }, function(){
            jQuery(this).removeClass('over');
        });
        this.titleContainer.click(function(e){
            self.toggle();
            e.preventDefault();
        });
    },
    
    switchTitle: function(){
         if (this.openedTitle.length) {
            if (this.titleContainer.hasClass('opened')){
                this.closedTitle.hide();
                this.openedTitle.show();
            }
            else {
                this.closedTitle.show();
                this.openedTitle.hide();
            }
        }    
    },
    
    open: function(){
        this.bodyHeight = this.body.children().outerHeight();
        if (this.groupNum) {
            for (var i = 0; i < accordionItems[this.groupNum].length; i++) {
                var ai=accordionItems[this.groupNum][i];
                if (ai.titleContainer.hasClass('opened') && ai != this) ai.close();
            }
        }
        this.titleContainer.addClass('opened');
        this.switchTitle();
        this.body.animate({
            opacity: 1,
            height: this.bodyHeight + 'px'
        }, {
            queue: false,
            duration: this.duration,
            complete: function(){
                jQuery(this).css({
                    height: 'auto'
                });
            }
        });
    },
    
    close: function(){
        var self = this;
        this.bodyHeight = this.body.height();
        this.body.animate({
            opacity: 0,
            height: 0
        }, {
            queue: false,
            duration: this.duration,
            complete: function(){
                self.titleContainer.removeClass('opened');
                self.switchTitle();
            }
        });
    },
    
    toggle: function(){
        if (this.titleContainer.hasClass('opened')) 
            this.close();
        else 
            this.open();
    }
}

var accordionItems = [];
function accordions(){
    jQuery('.accordionNode').each(function(){
        var groupNum = 0;
        var tmp = jQuery(this).attr('class').split(" ");
        for (var i = 0; i < tmp.length; i++) {
            if (tmp[i].indexOf('accordionGroup') != -1) {
                groupClass = tmp[i];
                groupNum = groupClass.split('accordionGroup-')[1];
            }
        }
        if (accordionItems[groupNum] == undefined) 
            accordionItems[groupNum] = [];
        var n = accordionItems[groupNum].length;
        accordionItems[groupNum][n] = new accordion(jQuery(this), groupNum);
        accordionItems[groupNum][n].init();
    });
    jQuery('.accordionLink').each(function(){
        jQuery(this).click(function(e){
            var tmp = jQuery(this).attr('rel').split(',');
            var group = tmp[0];
            var item = tmp[1] - 1;
            accordionItems[group][item].toggle();
            e.preventDefault();
        })
    });
}

function productSelect(){
    var is = jQuery('.thumbMenu a');
    is.each(function(i){
        var t=jQuery(this);
        t.data('pic',t.find('img').attr('src'));
        t.click(function(e){
            is.removeClass('active');
            t.addClass('active');
            var fullSize = t.data('pic').split('tn_');
            jQuery('.productPic').attr('src', fullSize[0] + fullSize[1]);
            e.preventDefault();
            fixPng();
        });    
    });
}

function partnerList(){
    var $sel=jQuery('#partnerFilter');
    jQuery('#partnerList h2 span').each(function(){
        var $opt=jQuery('<option value="'+jQuery(this).text()+'">'+jQuery(this).text()+'</option>');
        $sel.append($opt);
    });
    $sel.change(function(){
        var $v=jQuery(this).val();
        jQuery('#partnerList .defaultBox').each(function(){
            $ttl=jQuery(this).find('h2 span').text();
            if ($ttl!=$v && $v!='') jQuery(this).hide();
            else jQuery(this).show(); 
        });
    });
}

// Etalon Team árkalkulátor
function etalonTeamPriceCalculator(jref){
    var $ = jref;
    if ($('.etalonTeamIndex').length || $('.etalonTeam').length) {
        var conv = new formattedNumberConverter();	
        $('.subs').each(function(i){
            var $sel = $(this);
            $sel.change(function(){
                var $defPrice = $('.defPrice ').eq(i), 
                    defPrice = conv.convert($defPrice.html()), 
                    $discount = $('.discount').eq(i),
                    discount = conv.convert($discount.html()),
                    subs = $(this).val(),
                    $fullPrice = $('.fullPrice').eq(i),
                    fullPrice = conv.convert(defPrice + (subs * discount));    
                $fullPrice.html(fullPrice + ' Ft');
				
				//var prefix = '#full_' + $(this).val();
				//$('.fullPriceRow td').eq(i).find(prefix).addClass('active').siblings().removeClass('active');
            }).trigger('change');
        });
    }
}

function calcBusinessRates(){
    var cnt=jQuery('table.businessNet');
    if (cnt.length) {
        var $inps = jQuery('input[name="priceSelect"]'), 
            $prices = jQuery('#pContent .price span').addClass('netto'),
            $sel = jQuery('select.packageSelect'),
            $disCont = jQuery('div.cellContent.discount'),
            $res = jQuery('span.resultPrice');

        $disCont.find('input[type=checkbox]').click(function(){
            var $this = jQuery(this),
                cls = $this.attr('class'),
                prevImg = $this.parents('td.fullContentCenter').parent('tr').prev('tr').find('img')[0];
                imgSrc = prevImg.src;
            if (imgSrc.search(/-inactive/) > -1) {
                prevImg.src = imgSrc.replace(/-inactive/, '-active');
            }
            if (imgSrc.search(/-active/) > -1) {
                prevImg.src = imgSrc.replace(/-active/, '-inactive');
            }
            if (cls.length > 0) {
                if (jQuery(this).is(':checked')) {
                    jQuery('input#csoportonbelul').attr('checked', 1);
                }
                else {
                    jQuery('input#telematrix').attr('checked', 0);
                    var nextImg = jQuery('#resultMaxTop')[0];
                    nextImg.src = imgSrc.replace(/-active/, '-inactive');
                }
            }
            calcPrices();
        })
        
        function thousand(str){
            var s = String(str);
            if (str > 9999) {
                var reg = new RegExp('(-?[0-9]+)([0-9]{3}),?')
                while (reg.test(s)) {
                    s = s.replace(reg, '$1 $2');
                }
            }
            return s;
        }
        
        function stripNum(s,b){
            var parts=String(s).split(','),
                ret="",
                i=0;
            if (parts.length == 1) parts=String(s).split('.');
            
            // Ez azert kell, mert ragaszkodott hozza a megrendelo, hogy a 0,06-nak a bruttoja 0,08 legyen - a szamolas megtortenik elobb, de beirasra a kerekitett ertek kerul
            if (s == '0,075') {
                ret = '0,08';
            }
            else if (s == '0,064') {
                ret = '0,06';
            }
            else if (parts.length > 1) {
                i=parts[1].indexOf('0');
                if (!b) ret=parts[0] + "," + parts[1].slice(0, i==0?2:1);
                else ret=parts[0] + "," + parts[1].slice(0, i>0?i:3);
            }
            else ret=s;
            return ret;
        }
        
        function checkNetto(){
            var ckeckedInput = $inps.filter(':checked'),
                id = ckeckedInput.attr('id');
            ckeckedInput.siblings('label').addClass('coMag');
            $inps.not(':checked').siblings('label').removeClass('coMag');
            $prices.each(function(){
                var $t=jQuery(this),
                    val=$t.text().replace(' ', '').replace(',','.');
                    
                if (id == 'brutto' && $t.hasClass('netto')) {
                    $t.removeClass('netto').addClass('brutto');
                    $t.text(thousand(stripNum(String(val * 1.27).replace('.',','),$t.hasClass('noStrip'))));
                }
                else if (id == 'netto' && $t.hasClass('brutto')){
                    $t.removeClass('brutto').addClass('netto');
                    $t.text(thousand(stripNum(String(val * 0.7874015748031496).replace('.',','),$t.hasClass('noStrip'))));
                    
                }
            });
            calcPrices(true);
            
            // A statikusan beírt nettó és bruttó árak megjelenítése
			if( id == 'netto' ){
				jQuery('#pContent').find('.price_n').show();
				jQuery('#pContent').find('.price_b').hide();
			}else{
				jQuery('#pContent').find('.price_n').hide();
				jQuery('#pContent').find('.price_b').show();
			}
        }
        
        function calcPrices(withoutRoll){
            var sum = 0;
            $disCont.each(function(i){
                var $t = jQuery(this), 
                    $inp = $t.find('input[type=checkbox]'),
                    $val = $t.find('.price span'),
                    prevImg = $t.parents('td.fullContentCenter').parent('tr').prev('tr').find('img')[0],
                    imgSrc = prevImg.src;

                if ($inp.is(':checked')) {
                    if (imgSrc.search(/-inactive/) > -1) {
                        prevImg.src = imgSrc.replace(/-inactive/, '-active');
                    }
                    sum += $val.text().replace(',','.') * 1;
                    $t.addClass('active');
                }
                else $t.removeClass('active');
            });
            
            var timer = null;
                items = jQuery('div.cellContent.priceCell span:visible');
            
                if (timer!=null) clearTimeout(timer);
                var diff = ($res.eq(0).text().replace(',','.') * 1) - (sum + items.eq(0).text().replace(' ', '') * 1),
                    //delay = diff ? Math.round(1 / Math.abs(diff) * 200000) : 10;
                    //delay = 2000/((sum + items.eq(0).text().replace(' ', '') * 1)/10);
                    delay = 50;
                writePrice = function(){
                    timer = setTimeout(function(){
                        var equals = 0;
                        items.each(function(i){
                            var basicPrice = (jQuery(this).text().replace(' ', '').replace(',','.') * 1),
                                startPrice = ($res.eq(i).text().replace(' ', '').replace(',','.') * 1),
                                endPrice = sum + basicPrice,
                                increment = jQuery(this).attr('increment');

                            if (startPrice < endPrice) {
                                increment = increment*1 || 1000;
                                
                                if ((endPrice - startPrice) < increment && increment>10) {
                                    increment = increment/10;
                                    jQuery(this).attr('increment', increment)
                                }
                                startPrice += increment;
                                if (startPrice > endPrice) {
                                    startPrice = endPrice;
                                }
                            }
                            else if (startPrice > endPrice) {
                                increment = increment*1 || 1000;
                                if ((startPrice - endPrice) < increment && increment>10) {
                                    increment = increment/10;
                                    jQuery(this).attr('increment', increment)
                                }
                                startPrice -= increment;
                                if (startPrice < endPrice) {
                                    startPrice = endPrice;
                                }
                            }
                            $res.eq(i).text(thousand(stripNum(startPrice)));
                            if (startPrice == endPrice) {
                                jQuery(this).attr('increment', 1000)
                                equals++;
                            }
                            
                        });
                        if (equals!=items.length) {
                            writePrice();
                            return false;
                        }
                    }, delay);
                };
                writePrice();
        }

        function changePrices(){
            var $t = $sel.find(':selected'),
                parts = $t.attr('class').split('-'),
                label=jQuery('strong.chLabel'),
                bberry=jQuery('span.bberry');
                
            jQuery('strong.price.p_' + parts[1]).show().siblings().hide();
            if (parts[3] == 1) {
                jQuery('.SHforgalmi').show();
                jQuery('.SHbusiness').hide();
                bberry.addClass('hidden');
                bberry.next('.price_n').removeClass('hidden');
                bberry.next().next('.price_b').removeClass('hidden');                
            }
            else {
                jQuery('.SHforgalmi').hide();
                jQuery('.SHbusiness').show();
                bberry.removeClass('hidden');
                bberry.next('.price_n').addClass('hidden');
                bberry.next().next('.price_b').addClass('hidden');
            }
            bberry.text(parts[2]*(bberry.hasClass('brutto')?1.27:1));
            calcPrices(true);
        }

        function resultTable() {
            
            var win = jQuery(window),
                container = jQuery('#resultTableContainer'),
                table = jQuery('#resultTable'),
                winHeight = win.height(),
                className;

            win.scroll(function(){
                var scrollBottom = jQuery(window).scrollTop() + winHeight,
                    maxTopOffset =jQuery('#resultMaxTop').offset(),
                    maxTopPos =jQuery('#resultMaxTop').position(),
                    contOffset = container.offset(),
                    contHeight = container.height(),
                    contBottom = contOffset.top + contHeight;
                if (contBottom < scrollBottom) {
                    className = 'static';
                }
                else {
                    className = scrollBottom < (maxTopOffset.top + contHeight) ? 'absolute' : 'fixed';
                }
                table[0].className = className;
                table.css('top', (className == 'absolute') ? maxTopPos.top : 'auto');
            });
        }
        
        $inps.click(checkNetto);
        $sel.change(changePrices);
        checkNetto();
        changePrices();
        resultTable();
        jQuery('select.packageSelect').customSelect();
    }
}

function changeNetBrutPrices($){
    var $btn = $('.changeNetBrutPriceBtn');
    if($btn.length){
        var $prices = $('.priceToChangeNetBrut'); 
        $btn.click(function(e){
            var $t = $(this),
                type = this.rel,
                newType = type == 'netto' ? 'brutto' : 'netto';
            $prices.filter('.'+newType).each(function(){
                var $t = $(this),
                    actPrice = $t.html() * 1,
                    newPrice = actPrice * (newType == 'brutto' ? 0.7874015748031496 : 1.27);
                $t.html(newPrice).addClass(type).removeClass(newType);
            });
            $btn.css('text-decoration','underline').html('átváltok ' + (newType == 'brutto' ? 'bruttó' : 'nettó') + ' díjra');
            $t.css('text-decoration','none').html((newType == 'netto' ? 'bruttó' : 'nettó') + ' díj'); 
            e.preventDefault();
        }).filter(function(){
            return this.rel == 'brutto'
        }).css('text-decoration','underline');
    }
}

/* jQuery ACCORDION end */

/* jQuery city filter start */

function hotelCityFilter() {
    jQuery(document).ready(function() {
        var $hotelCities = jQuery('select#hotelCities');
        $hotelCities.val('all');
        $hotelCities.change(function() {
            jQuery('ul#hotelCityList li.selectedItem').removeClass('selectedItem');
            if ($hotelCities.val() == 'all') {
                jQuery('ul#hotelCityList').css({ 'height': 'auto' });
                jQuery('ul#hotelCityList li').fadeIn();
            }
            else {
                jQuery('ul#hotelCityList li:not(#' + $hotelCities.val() + ')').hide();
                jQuery('ul#hotelCityList').animate({ 'height': jQuery('ul#hotelCityList li#' + $hotelCities.val()).height() }, 200 , function()  {
                    jQuery('ul#hotelCityList li#' + $hotelCities.val()).fadeIn('normal').addClass('selectedItem');
                });
            }
        });
    });
}

/* jQuery city filter end */


/* ÁRFORMÁZÓ */
var formattedNumberConverter = function() {
};
formattedNumberConverter.prototype = {
    convert : function(toConvert) {
        
        if (typeof toConvert == 'string') { //megnezzuk a tipusat, ha sztring, akkor a szamma alakito fuggvenyt hivjuk meg
            var converted = this.formattedStringToNumber(toConvert);
        }
        else if (typeof toConvert == 'number') { //ha szam, akkor a sztringge alakito fuggvenyt hivjuk meg
            var converted = this.formatNumberToString(toConvert);
        }
        else {
            return 'Hibás paraméter';
        }
        return converted; //visszaadjuk a konvertalt erteket
    },

    formattedStringToNumber : function(string) {
        return parseFloat(string.replace(/\s/g, '').replace(',','.')); //kivesszuk a szokozt, es a biztonsag kedveert tipuskonverziot is csinalunk
    },

    formatNumberToString : function(number) {
        number = number.toFixed(2);
        if (number < 1000) { //ha kisebb mint 1000, nincs dolgunk
            number = number + ''; //csak sztringet csinalunk belole
            return number.replace('.',',');
        }
        else {
            number = number + ''; //sztringet csinalunk belole
            number = number.split('.');
            var tempArray = [],
                j = 0;
                
            if (number[1]) {
                tempArray = number[1].split('').slice(0,2);
                tempArray.unshift(',');
            }
            number = number[0].split('');
            for (var i = number.length - 1; i >= 0; i--) { //hatulrol kezdve vegigmegyunk rajta
                j++; //ebbol fogjuk tudni, hogy epp harom karakter utan vagyunk-e
                tempArray.unshift(number[i]); //mindenkeppen belerakjuk a temporary tomb elejere az eredei szamot
                if (j % 3 == 0) { //ha harom karakter utan vagyunk
                    tempArray.unshift(' '); //belerakunk egy szokozt is
                    j = 0; //es kinullazzuk a harmas szamlalot
                }
            }
            return tempArray.join(''); //a vegen osszejoinoljuk egy valtozova a tombot
        }
    }
};

function setEqualHeight(){
    var equalHeightContainers = jQuery('.setEqualHeight');
    var equalHeightBoxes = new Array();
    
    for (var i = 0; i < equalHeightContainers.length; i++) {
        var equalHeightBoxes = jQuery(equalHeightContainers[i]).find('.equalHeight');
        var maxHeight = 0;
        for (var j = 0; j < equalHeightBoxes.length; j++) {
            if (jQuery(equalHeightBoxes[j]).outerHeight() > maxHeight) {
                maxHeight = jQuery(equalHeightBoxes[j]).outerHeight();
            }
        }
        for (var j = 0; j < equalHeightBoxes.length; j++) {
            jQuery(equalHeightBoxes[j]).css({
                'height': maxHeight - parseInt(jQuery(equalHeightBoxes[j]).css('padding-top')) - parseInt(jQuery(equalHeightBoxes[j]).css('padding-bottom')) - parseInt(jQuery(equalHeightBoxes[j]).css('border-bottom-width')) - parseInt(jQuery(equalHeightBoxes[j]).css('border-top-width')) + 'px'
            });
        }
    }
}



function loginTooltip(){
    
    var gZindex = 1000;
    
    jQuery(".tooltipLink").click(function(event){
        event.preventDefault();
        var matches = jQuery(this).attr('class').match(/posL([-]*?\d{1,4}|auto|right)T([-]*?\d{1,4}|auto)_(\d{1,4})/);
        var cont = jQuery(this).parents('.tooltipContainer').eq(0);
            cont.css({
                position: 'relative'
            });
        if (matches != null) {
            var fpass = jQuery("#js_tooltip_"+matches[3]);
            jQuery('body').append(fpass);
            
            if (matches[1] == 'auto') {
                matches[1] = (jQuery(this).position().left - Math.round(fpass.width() / 2) + Math.floor(jQuery(this).width() / 2) - 2);
            }
            if (matches[1] == 'right') {
                matches[1] = (jQuery(this).position().left - Math.round(fpass.width()) + Math.floor(jQuery(this).width() / 2) + 41);
            }
            if (matches[2] == 'auto') {
                matches[2] = jQuery(this).position().top + jQuery(this).height() + 3;
            }
            
            fpass.css({
                left: cont.offset().left+ (matches[1]*1) + "px",
                top: cont.offset().top+ (matches[2]*1) + "px",
                zIndex: gZindex++
            });
            
            if (jQuery.browser.msie &&
            jQuery.browser.version <= 6) {
                var frm = fpass.prev('iframe');
                if (frm.length == 0) {
                    frm = jQuery('<iframe>');
                    fpass.before(frm);
                }
                frm.css({
                    position: 'absolute',
                    opacity: 0,
                    marginTop: '10px',
                    left: matches[1] + "px",
                    top: (matches[2]) + "px",
                    width: fpass.width() + "px",
                    height: (fpass.height() - 10) + "px",
                    zIndex: 1
                });
            }
            
            jQuery(".tooltipBox").not("#js_tooltip_" +
            matches[3]).fadeOut("fast", function(){
                jQuery(this).parents().filter('.tooltipContainer').css({
                    position: 'static'
                });
            });
            
            fpass.fadeIn('fast');
            fpass.find(".close").click(function(event){
                fpass.fadeOut("fast", function(){
                    cont.css({
                        position: 'static'
                    });
                });
                event.preventDefault();
            });
            
            event.stopPropagation();
            
            jQuery(document).click(function(ev){
                var onclk = false;
                fpass.find("*").each(function(){
                    if (this == ev.target) 
                        onclk = true;
                })
                if (!onclk) {
                    fpass.fadeOut("fast", function(){
                        cont.css({
                            position: 'static'
                        });
                    });
                }
            });
        }
    });
}

function initializeTooltip(){
    var t = jQuery('.advTooltipLink');
    if (t.length) {
        t.tooltip({
            delay: 0,
            fade: 400,
            trigger: 'click',
            pushX: 0,
            pushY: 0,
            closeTpl: '<a href="#" class="coMag close"><span class="fontSize11 floatLeft">Bezárás</span><img width="12" height="12" src="/static/img/icons/ico_mag-x.gif" alt="" title=""></a>',
            cont: function(p){
                var tt = p.parent().next('.tooltipBox');
                tt.remove();
                return tt.find('.tooltipGroup, .myTtooltipGroup');
            }
        });
    }
}

// Akciós mobiltelefon árlista készülék választó
    
function mobileListSelect() {
    var $pricelist = jQuery('.mobilePriceList');
    if ($pricelist.length) {
        
        if ($pricelist.find('.tabPanelsWrapper.fakeTabs a.tab').eq(0).hasClass('clicked')){
            $pricelist.find('.discountCont').addClass('domino');
            $pricelist.find('table.mobileTable').addClass('domino');    
        }
        
        var $posSetFixed = jQuery('.mobilePriceList').find('.whiteBg'),
            boxOffsetTop = $posSetFixed.offset().top,
            boxHeight = $posSetFixed.height(),
            $fakeDiv = jQuery('<div />').css('height',boxHeight).addClass('contentHeaderPlaceholder'),
            scrTop = 0;
            $headings = $pricelist.find('h2'),
            headlist = [],
            $posSetFixed.parents('.mobilePriceList').css('z-index',2).end().find(".discountCont").append(jQuery(".mobilePriceList table.discountTableHeader"));
        
        
        $headings.each(function(){
            var t = jQuery(this);
            headlist.push({
                id: t.attr('id'),
                top: t.offset().top
            });
        })    
            
        function setFixedElements(){
            scrTop = jQuery(window).scrollTop();
            if (scrTop >= boxOffsetTop) {
                if(!$posSetFixed.prev('.contentHeaderPlaceholder').length) $posSetFixed.addClass('fixed').before($fakeDiv);
            }
            else {
                $posSetFixed.removeClass('fixed');
                $fakeDiv.remove();
            }
        }
        
        function setCategory(){
            var top = jQuery(window).scrollTop() + boxHeight + 15;
            for (var i = 0; i < headlist.length; i++){
                if (top >= headlist[i].top && ((headlist[i + 1] && top < headlist[i + 1].top || !headlist[i + 1]))) {
                    $link.text($phoneLabel.filter('[href=#' + headlist[i].id + ']').text());
                }
                else {
                    if (!headlist[i] || top<=boxOffsetTop+boxHeight) $link.text('Válassz gyártót');
                }
            };
        }
        
        setFixedElements();
        
        jQuery(window).scroll(function(e){
            setCategory();
            setFixedElements();
        });
        
        var $box = jQuery('.mobilePriceList .discountTableHeader .chooserBox');
        var $link = $box.find('a.choose');
        var $list = $box.find('ul');
        var $phoneLabel = jQuery("div.chooserBox ul li a");
        var windowHeight = jQuery(window).height();
        
        $link.click(function(e){
            var $t = jQuery(this);
            if ($t.parent().is('.opened')) {
                $box.removeClass('closed').removeClass('opened');
                $list.removeClass('closed').removeClass('opened');
                $link.removeClass('closed').removeClass('opened');
                
                $t.parent().addClass('closed');
                $t.parent().find('ul').addClass('closed');
                $t.parent().find('a.choose').addClass('closed');
                
            }
            else {
                $box.removeClass('closed').removeClass('opened');
                $list.removeClass('closed').removeClass('opened');
                $link.removeClass('closed').removeClass('opened');
                
                $t.parent().removeClass('closed').addClass('opened');
                $t.parent().find('ul').removeClass('closed').addClass('opened');
                $t.parent().find('a.choose').addClass('opened');
                
            }
            e.preventDefault();
        });
        
        $phoneLabel.click(function(e){
            if (this.href.search('#') > -1) {
                e.preventDefault();
                var $t = jQuery(this),
                    $actualTitle = jQuery('h2#' + this.href.split('#')[1]),
                    actualTitleOffsetTop = $actualTitle.offset().top;
                
                $t.parents('div.chooserBox').find('a.choose').text($t.text());
                $box.removeClass('opened');
                $list.removeClass('opened');
                
                $t.parents('div.chooserBox').addClass('closed');
                jQuery(window).scrollTop(actualTitleOffsetTop - boxHeight);
                setCategory();
            }
        });
        
        /*var reg = new RegExp("(MSIE )(\\d+(\\.\\d+)*)");
        ret = reg.exec(navigator.userAgent);*/
       
        var ie = jQuery.browser.msie && parseInt(jQuery.browser.version)==7;
        
        //alert(jQuery.browser.version)
        
        jQuery('.tabPanelsWrapper .mobileTable tr').each(function(){
            var tr = jQuery(this),
                lnk = tr.find('.productLink').attr('href'),
                poser = tr.find('.productLayer'),
                layer = tr.find('.productPic'),
                w = layer.outerWidth(),
                h = layer.outerHeight(),
                timer = null;
                
            tr.mouseenter(function(){
                tr.addClass('hovered');
                timer = setTimeout(function(){
                    layer.css({
                        height:0,
                        overflow: 'hidden'
                    });
                    
                    poser.css({
                        visibility: 'visible',
                        width:0,
                        height: tr.find('> td').innerHeight(),
                        left:0,
                        top: (tr.find('.cell').outerHeight()-tr.find('> td').height())/2,
                        overflow: 'visible'
                    }).animate({
                        left: 0-w-10,
                        width: w
                    }, {
                        duration: 200,
                        queue: false,
                        complete: function(){
                            layer.animate({
                                height:h
                            }, {
                                duration: 300,
                                queue: false,
                                complete: function(){
                                
                                }
                            });
                        }
                    })
                }, 400);
                
                if (windowHeight < tr.offset().top - scrTop + h) {
                    layer.addClass('up');
                }
                else 
                    layer.removeClass('up');
            }).mouseleave(function(){
                tr.removeClass('hovered');
                clearTimeout(timer);
                poser.css({
                    visibility: 'hidden'
                });
            });
            
            tr.click(function(){
                window.location.href = lnk;
            });
        });
        
        jQuery('.discountHelp').tooltip({
            delay: 0,
            fade: 400,
            cls: 'discountHelp',
            trigger: 'click',
            hook: 'right-bottom',
            pushX: -2,
            pushY: 5,
            closeTpl: '<a href="#" class="coMag close"><span class="fontSize11 floatLeft">Bezárás</span><img width="12" height="12" src="/static/img/icons/ico_mag-x.gif" alt="" title=""></a>',
            cont: function($help){
               return $help.parents('a.tab').next().html();
            }
        });
        
        /*jQuery('.productLink').bind('mouseenter mouseleave',function(e){
            var $t = jQuery(this),
                $layer = $t.parents('.cell').find('.productLayer');
            if($layer.length){
                $layer.toggle();
            }
        });*/
        
    }
}

function tabPanels(){
    var $tabBoxes = jQuery('.tabPanelsWrapper:not(.fakeTabs)');
    if ($tabBoxes.length) {
        $tabBoxes.each(function(){
            var $tabBox = jQuery(this),
                $tabs = $tabBox.find('.tab');
                
            $tabs.each(function(){
                var t = jQuery(this),
                    a = t.find('a').length>0?t.find('a'):t;
                   
                if (location.hash == a.attr('href') && a.attr('href')!="#") t.addClass('clicked');
                 
                t.click(function(e){
                
                    // i-ben tároljuk hanyadik tabra kattintottunk
                    var i = jQuery.inArray(this, jQuery.makeArray($tabs));
                    
                    $tabs.removeClass('clicked');
                    t.addClass('clicked');
                    
                    if (a.attr('href')!="#") location.hash = a.attr('href');
                    
                    // i-edik contentet mutatjuk, a többit elrejtjük
                    $tabBox.find('.tabContent').addClass('hided').removeClass('showed').eq(i).addClass('showed').removeClass('hided');
                    
                    e.preventDefault();
                    e.stopPropagation();
                });
            });
            
            // inaktívról levesszük a clicket, majd letiltjuk
            $tabBox.find('.inactive').unbind('click').click(function(){
                return false;
            });
            if ($tabs.filter('.clicked').length == 0){
                $tabs.eq(0).addClass('clicked');
            } 
            
            $tabs.filter('.clicked').trigger('click');
        });
    }
}

function roundBoxLinks(){
    var boxes = jQuery('.gradRoundBox');
    boxes.each(function(){
        var box = jQuery(this),
            links = box.find('a');
        if (links.length == 1){
            var link = links.eq(0);
            box.click(function(e){
                e.preventDefault();
                location.href=link.attr('href');
            })
            box.mouseover(function(){
                box.css({cursor:'pointer'});
                link.addClass('hover');
            })
            box.mouseout(function(){
                box.css({cursor:'normal'});
                link.removeClass('hover');
            })
        }    
    });
    
    var items = jQuery('.discountItems .roundedItem, ul.iconMenu li');
    items.each(function(){
        var box = jQuery(this),
            links = box.find('a');
        if (links.length == 1){
            var link = links.eq(0);
            box.click(function(e){
                e.preventDefault();
                location.href=link.attr('href');
            })
            box.mouseover(function(){
                box.addClass('hover');
            })
            box.mouseout(function(){
                box.removeClass('hover');
            })
        }    
    });
}

function layerHelp(){
     
    jQuery('.husegprogramPages span.layerHelp').click(function(e){
        e.preventDefault();
        e.stopPropagation();
        var dlg = jQuery("#dialog");
        if (!dlg.length) {
            dlg = jQuery('<div id="dialog">');
            jQuery('body').append(dlg);
        }
        dlg.html(jQuery(this).parents('a').next('.dialogContent').html());
        dlg.dialog({
            bgiframe: true,
            width: 630,
            minHeight: 100,
            modal: true,
            position: 'center',
            zIndex: 5000,
            closeOnEscape: true,
            closeText: 'Ablak bezárása',
            close: function(){
                dlg.dialog('destroy');
                dlg.replaceWith('<div id="dialog"></div>');
            },
            open: function(event, ui) {
                dlg.find('a.closeLink').click(function(e){
                    e.preventDefault();
                    dlg.dialog('close');
                })   
            }
        });
        
    }).hover(function(){
        jQuery(this).addClass('hovered');
    },function(){
        jQuery(this).removeClass('hovered');
    });
}

function snappingContentHeaders(){
    
    var $snappingContentHeaders = jQuery('.snappingContentHeaders');
    
    if($snappingContentHeaders.length){
        
        $snappingContentHeaders.each(function(){
            
            var $t = jQuery(this),
                $fixedOnScroll = $t.find('.fixedOnScroll'),
                $movingOnScroll = $t.find('.movingOnScroll'),
                fixedOuterHeight = $fixedOnScroll.outerHeight(),
                fixedOffsetTop = $fixedOnScroll.offset().top,
                fixedOffsetBottom = fixedOffsetTop + fixedOuterHeight,
                movingOuterHeight = $movingOnScroll.outerHeight(true),
                movingOffsetTop = $movingOnScroll.offset().top,
                movingOffsetBottom = (movingOffsetTop + movingOuterHeight) - ((movingOffsetTop + movingOuterHeight) - ($movingOnScroll.find('.endSnap').offset().top || 0)),
                $fakeDiv = jQuery('<div />').css('height',fixedOuterHeight).addClass('contentHeaderPlaceholder'),
                scrTop = 0,
                reachedTheBottom = false;
                
            function setFixedOnScrollOptions(cssClassMethod,cssClass,topValue,isAtBottom){
                $fixedOnScroll[cssClassMethod](cssClass).css('top',topValue);
                reachedTheBottom = isAtBottom;
            }
                
            function setFixedOnScroll(){
                
                scrTop = jQuery(window).scrollTop();
                if (scrTop >= fixedOffsetTop) {
                    
                    if(!$fixedOnScroll.prev('.contentHeaderPlaceholder').length) $fixedOnScroll.addClass('fixed').before($fakeDiv);
                    
                    if((scrTop+fixedOuterHeight) >= movingOffsetBottom && !reachedTheBottom){
                        if(scrTop > (movingOffsetBottom-fixedOuterHeight))scrTop = movingOffsetBottom-fixedOuterHeight;
                        setFixedOnScrollOptions('addClass','absolute',scrTop,true)
                        
                    } else if(scrTop <= $fixedOnScroll.offset().top){
                        
                        setFixedOnScrollOptions('removeClass','absolute',0,false)
                        
                    }
                    
                } else {
                    
                    setFixedOnScrollOptions('removeClass','fixed',0,false)
                    $fakeDiv.remove();
                    
                }
            }
            
            if(movingOuterHeight >= 250){
                setFixedOnScroll();
                
                jQuery(window).bind('scroll',function(e){
                    setFixedOnScroll();
                });
            }
            
        });
    }
}

function radioNetto(){
    
     function writePrice(item, startPrice, targetPrice, step, o){
         var actualPrice = startPrice;
         
         timer = setTimeout(function(){
            actualPrice+=step;
            item.text(thousand(actualPrice));
            
            if ((step>0 && actualPrice>targetPrice) || 
            (step<0 && actualPrice<targetPrice)){
                item.text(thousand(targetPrice));  
                o.removeClass('run');  
            }
            else {
                writePrice(item, actualPrice, targetPrice, step, o);    
            }
         
         }, 30);
     };
     
     function thousand(str){
         var s = String(str);
         if (str > 9999) {
             var reg = new RegExp('(-?[0-9]+)([0-9]{3}),?')
             while (reg.test(s)) {
                 s = s.replace(reg, '$1 $2');
             }
         }
         return s;
     }
    
    function calcPrices(o,netto,cnt){
        var prices = o.parents('table').find('var.calcPrice'),
            reg = new RegExp('(-?[0-9]+)([0-9]{3})$');
            
        cnt.addClass('run');
        prices.each(function(){
            var t = jQuery(this),
                b = t.text().replace(/[\s\t\n\r]/gm, '') * 1; 
                e = Math.round(b * (netto ? 0.7874015748031496 : 1.27)), 
                str = String(e),
                step = Math.round((e-b)/10);

            writePrice(t,b,e,step,cnt);
        });
    }
    
    jQuery('.husegprogramPages .priceType').each(function(){
        var cnt = jQuery(this), first = true;
        
        cnt.find('input[type=radio]:not(.fixed)').each(function(){
            var t = jQuery(this), p = t.wrap(jQuery('<div>').addClass('customRadioBox')).parent(), l = jQuery('label[for=' + t.attr('id') + ']'), s = jQuery('input[name=' + t.attr('name') + ']').not(t);
            
            t.addClass('fixed').css({
                opacity: 0
            });
            
            t.click(function(){
                if (t.attr('checked') && !p.hasClass('checked') && !cnt.hasClass('run')) {
                    var netto = t.attr('id').indexOf('netto') > -1;
                    s.each(function(){
                        jQuery(this).parent().removeClass('checked');
                        jQuery('label[for=' + jQuery(this).attr('id') + ']').removeClass('bold');
                    });
                    p.addClass('checked');
                    l.addClass('bold');
                    if (first && netto) {
                        return false;
                    }
                    first = false;
                    calcPrices(t, netto, cnt);
                }
            });
            
            p.add(l).hover(function(){
                p.addClass('hovered');
            }, function(){
                p.removeClass('hovered');
            });
            
            if (t.attr('checked')) {
                t.trigger('click');
            }
            
        });
    });
}

function gallerySlider(){
        var element = jQuery('.husegprogramPages div.gallery');
        if (element.length) {
            var visibleElements = 5,
                actualPageIndex = 0,
                prev = jQuery('<a href="#" class="prev">&nbsp;</a>').appendTo(element),
                next = jQuery('<a href="#" class="next">&nbsp;</a>').appendTo(element),
                sliderCnt = element.find('.slideContent'),
                sw = sliderCnt.width(),
                hw = sw/2,
                sliderContent = element.find('ul.sliderContainer'),
                slide = sliderContent.find('li'),
                slideLink = slide.find('a'),
                sliderWidth = 0;
                
            function setActive(index){
                var prev = slide.index(slide.filter('.active')),
                    active = slide.removeClass('active').eq(index),
                    aw = active.width()/2, 
                    l = active.position().left,
                    left = 0;
                
                active.addClass('active');
                
                if (prev<index){ //jobbra
                    left = 0;
                    if (hw<l){
                        left = -l + hw - aw;
                    }
                    if ((sliderWidth - hw) < l) {
                        left = -sliderWidth + sw;
                    }
                    
                }
                if (prev > index) { //balra
                    left = -sliderWidth + sw;
                    if (hw > l) {
                        left = 0;
                    }
                    else {
                        if ((sliderWidth - hw) > l) {
                            left = -l + hw - aw;
                        }
                    }
                }
                
                sliderContent.animate({
                    left: left
                }, {
                    queue: false,
                    duration: 500
                });
                
            }
            
            slide.each(function(){
                sliderWidth+=jQuery(this).outerWidth(true);    
            });
            setActive(actualPageIndex);
            sliderContent.css({
                left: 0
            }).width(sliderWidth);
            
            slideLink.click(function(e){
                var $t = jQuery(this);
                actualPageIndex = slide.index($t.parent());
                setActive(actualPageIndex);
                e.preventDefault();
            });
            
            next.click(function(e){
                if (actualPageIndex < slide.length-1) {
                    actualPageIndex++;
                    setActive(actualPageIndex);
                }
                e.preventDefault();
            });
            
            prev.click(function(e){
                if (actualPageIndex > 0) {
                    actualPageIndex--;
                    setActive(actualPageIndex);
                }
                e.preventDefault();
            });
            
            jQuery('div#cboxPrevious').live('click',function(){
                prev.trigger('click');
            });
            jQuery('div#cboxNext').live('click',function(){
                next.trigger('click');
            });
        }
    }
    
    function gallerySlideShowInitializer(){
        var gal = jQuery("div.gallery");
        if (gal.length > 0) {
            gal.find("li a").colorbox({
                previous: "Előző kép",
                next: "Következő kép",
                current: function(){
                    return jQuery(this).children('img').attr('alt');
                },
                opacity: 0.7,
                loop: false,
                initialWidth: 100,
                initialHeight: 75
            });
        }
    }
 function niceFormsInit(){
     var forms = jQuery('form[name=manufacturer], form[name=partnerSelectForm]');
     if (forms.length>0){
        forms.niceform();    
     }
 }

jQuery(document).ready(function(){
    niceFormsInit();
    gallerySlideShowInitializer();
    gallerySlider();
    radioNetto();
    accordions();
    productSelect();
    partnerList();
    etalonTeamPriceCalculator(jQuery);
    setEqualHeight();
    calcBusinessRates();
    changeNetBrutPrices(jQuery);
    //loginTooltip();
    roundBoxLinks();
    initializeTooltip();
    tabPanels();
    mobileListSelect();
    layerHelp();
    snappingContentHeaders();
    jQuery("input[name=tsearchQ]").clearInputs("Keresés");
});

function loadOtherPage(url){
    window.location.href = url;
}


/**
 * @author Kirowski Zrt.
 * @Copyright 2010 Kirowski Zrt. 
 */
(function($){
    
    // Extend jQuery element method
    $.fn.extend({
        check: function(){
            return jQuery(this).attr('checked',true);
        },
        uncheck: function(){
            return jQuery(this).attr('checked',false);
        },
        select: function(){
            return jQuery(this).attr('selected','selected');
        },
        deselect: function(){
            return jQuery(this).removeAttr('selected');
        },
        disable: function(){
            return jQuery(this).attr('disabled','disabled').removeAttr('enabled');
        },
        enable: function(){
            return jQuery(this).attr('enabled','enabled').removeAttr('disabled');
        },
        clearInputs: function(a){
            return $(this).each(function(){
                var $t = $(this),
                d = a || $t.val() || $t.text();
                if(!$t.val() || $t.val() == '')$t.val(d);
                $t.focus(function(){
                    var b = $(this);
                    if(b.val() == d)b.val("");
                    b.removeClass("error");
                }).blur(function(){
                    var b = $(this);
                    if (b.val() == d || b.val() == "")b.val(d);
                    b.removeClass("error");
                }).parents('form').submit(function(){
                    if ($t.val() == d) {
                        $t.val('');
                    }
                });
            });
        }
    })
})(jQuery);


