var triggerRankings;

(function( $ ){
  
  var sponsorRotateIndex = 0;
  var sponsorRotateCount;
  
  $.fn.rotateSponsors = function() {
    var lis = $('#sponsors_rotator > ul').children();
    $(lis).hide();$(lis[0]).fadeIn(800);
    sponsorRotateCount = $(lis).size();
    setInterval('$.fn.rotate()',4500);
  };
  
  $.fn.rotate = function(){
    $($('#sponsors_rotator > ul').children()[sponsorRotateIndex]).fadeOut(700);
    if (sponsorRotateIndex+1 >= sponsorRotateCount) {
        sponsorRotateIndex = -1;
    }     
    $($('#sponsors_rotator > ul').children()[sponsorRotateIndex+1]).fadeIn(350);
    sponsorRotateIndex++;
  }
  
})( jQuery );




$(document).ready(function(){
    $.fn.rotateSponsors();
    
    // aktiv menupont elotti vonal
    var menuItems = $('#menu-iwf > li');
    var prevItem;
    $.each(menuItems,function(key,value){
        if ($(this).hasClass('current-menu-item') || $(this).hasClass('current-menu-parent') || $(this).hasClass('current-post-ancestor')) {
            if (prevItem) { prevItem.addClass('clear-menu-item-bg');return false; }
        }
        prevItem = $(this);
    });
    
    // calendar toggle
    $('#calendar_ul > li > h6').click(function(){
    	$(this).parent().find('table').toggle();
    	//alert('k');
    });
    
    // sidebar calendar
    $('#calendar_container div.eventon, #calendar_container div.eventonm').live('click',function(){
        // osszes elrejtese, atszinezese
        $('div.c_rk_week_n').hide();
        $('div.eventon,div.eventonm').removeClass('eventactive');
        $(this).addClass('eventactive');
        var c = '<strong class="calendardatetitle">'+$(this).attr("title")+'</strong>';
        
        // esemenyek ezen a napon
        $.each(sidebarcal_days[parseInt($(this).find('em').html())],function(key,value) {
            //console.log(key+': '+value);
            c += '<div><b>'+sidebarcal_events[value]['event']+'</b>'+sidebarcal_events[value]['place']+' - '+sidebarcal_events[value]['nation']+' &nbsp; / &nbsp; '+sidebarcal_events[value]['date']+'</div>';
        });
        
        $('#'+$(this).attr("rel")+'_c').html(c).show();
        
        // aznap eltavolitasa
        $('div.ctoday').addClass("ctodayoff");
    });
    /*$('#cal_ttl').click(function(){
        $('div.c_rk_week_n').hide();$('div.eventon,div.eventonm').removeClass('eventactive');showCal('home');
    });*/
    
    // federations
    $("#federations_map ul li").hover(
        function(){
            $(this).addClass('hover');
        },
        function(){
            $(this).removeClass('hover');        
        }
    );
    $("#federations_title h2 a").hover(
        function(){
            $('li#'+$(this).attr("rel")).addClass("hover");  
        },
        function(){
            $('li#'+$(this).attr("rel")).removeClass("hover");          
        }
    );
    $("#federations_table tr").hover(
        function(){
            $(this).addClass("hover");
        },
        function() {
            $(this).removeClass("hover");
        }
    );
    $("#federations_table tr").click(function(){
        window.location = $(this).find('td').find('a').attr("href");
    });
    
    // sinclair
    $('#sinclair_female').click(function(){
        $(this).addClass('selected');$('#sinclair_male').removeClass('selected');$('#sinclair_sex').val('f');
    });
    $('#sinclair_male').click(function(){
        $(this).addClass('selected');$('#sinclair_female').removeClass('selected');$('#sinclair_sex').val('m');
    });
    $("#sinclair_submit").click(function(){
        var weight = $('#sinclair_weight').val();
        var total  = $('#sinclair_total').val();
        var sex    = $('#sinclair_sex').val();
        var A      = (sex=='m')?0.784780654:1.056683941;
        var b      = (sex=='m')?173.961:125.441;
        var X      = (Math.log(weight/b))/(Math.log(10));
        var AX2    = A*(X*X);
        var SC     = Math.pow(10,AX2);
        var SCTotal= Math.round((SC*total)*100)/100;

        if (!isNaN(SCTotal) != 0) {
            $('#sinclair_result > em').html(SCTotal);
            $('#sinclair_result').css('visibility','visible');
        } else { 
            $('#sinclair_result').css('visibility','hidden');
        }
        
    });
    
    
    // results
    $('#results_womens_total').click(function(){
        $('#men_total').hide();
        $('#men_snatchjerk').hide();
        $('#women_snatchjerk').hide();
        $('#women_total').show();
        $(this).removeClass('inactive_main');
        $('#results_mens_total').addClass('inactive_main');
        $('#results_mens_snatch').removeClass('active_main');
        $('#results_womens_snatch').removeClass('active_main');
    });
    $('#results_mens_total').click(function(){
        $('#women_total').hide();        
        $('#men_snatchjerk').hide();
        $('#women_snatchjerk').hide();
        $('#men_total').show();
        $(this).removeClass('inactive_main');
        $('#results_womens_total').addClass('inactive_main');
        $('#results_mens_snatch').removeClass('active_main');
        $('#results_womens_snatch').removeClass('active_main');
    });
    $('#results_mens_snatch').click(function(){
        $('#women_total').hide();
        $('#women_snatchjerk').hide();
        $('#men_total').hide();
        $('#men_snatchjerk').show();
        $('#results_womens_total').addClass('inactive_main');
        $('#results_mens_total').addClass('inactive_main');
        $(this).addClass('active_main');
        $('#results_womens_snatch').removeClass('active_main');
    });
    $('#results_womens_snatch').click(function(){
        $('#men_snatchjerk').hide();
        $('#women_total').hide();
        $('#men_total').hide();
        $('#women_snatchjerk').show();
        $('#results_mens_total').addClass('inactive_main');
        $('#results_womens_total').addClass('inactive_main');
        $(this).addClass('active_main');
        $('#results_mens_snatch').removeClass('active_main');
    });
    
    
    
    // STORE
    $('div.store_item').click(function(){
        var si = 1;
        if ($(this).hasClass('store_item_2')) { si=2; }
        if ($(this).hasClass('store_item_3')) { si=3; }
        if ($(this).hasClass('store_item_4')) { si=4; }
    
    
        $('div.store_item_row').hide().removeClass('rowclass1').removeClass('rowclass2').removeClass('rowclass3').removeClass('rowclass4');
        $('#'+$(this).attr("rel") + ' em > span').html($(this).find('h3').html());
        $('#'+$(this).attr("rel") + ' h2').html($(this).find('h2').html());
        $('#'+$(this).attr("rel")).addClass('rowclass'+si).show();
        
        $('#paypal_item').val($(this).find('h1').html());
        $('#paypal_amount').val($(this).find('h3').html());
        
    });
    
    $('span.store_btn').click(function(){ 
        window.location = 'https://www.paypal.com/cgi-bin/webscr?cmd=_xclick&business='+$('#paypal_business').val()+'&item_name='+escape($('#paypal_item').val())+'&item_number=1&amount='+$('#paypal_amount').val()+'&currency_code=USD&return='+escape($('#paypal_return').val())+'&cancel_return='+escape($('#paypal_cancel_return').val());
    });
    
    
    
    
    var showCal = function(data) {
        $.ajax({
       		type: "POST",
       		dataType: "json",
       		url: "/wp-content/themes/iwf/misc/sidebar_calendar.php",
       		data: 'data='+$('#sb_cal_current').html()+'&pn='+data,
       		success: function(json) {
       			if (json.response == 'error') {
       			  // hiba
       			} else {
       			 $('#sb_cal_current').html(json.monthC);
       			 $('#cal_month').html(json.monthTitle);
       			 $('#cal_json').html(json.content);
       			 sidebarcal_days = json.sidebarcal_days;
       			 sidebarcal_events = json.sidebarcal_events;
       			}
       		}       		
        });
    }
    
    // cal_home
    $('#cright #cal_next').click(function(){
        showCal('next');
    });
    $('#cright #cal_prev').click(function(){
        showCal('prev');
    });
    $('.clck_nextmonth').live('click',function(){
        showCal('next');
    });
    $('.clck_prevmonth').live('click',function(){
        showCal('prev');
    });
    
    
    // rankings
    triggerRankings = function(){
    
    	var $_GET = {};
    	document.location.search.replace(/\??(?:([^=]+)=([^&]*)&?)/g, function () {
    	function decode(s) {
        return decodeURIComponent(s.split("+").join(" "));
        }
        $_GET[decode(arguments[1])] = decode(arguments[2]);
        });
    
    	$('#ranking_category').find('option').remove();
    	if ($('#ranking_agegroup').val() != 'all' && $('#ranking_gender').val() != 'all') {
    		$('#ranking_category').append($("<option></option>").attr("value",'all').text('All'));
    		var ageGroup = $('#ranking_agegroup').val().toLowerCase();
    		var gender = $('#ranking_gender').val().toLowerCase();
    		$.each(rankingCategories[ageGroup][gender], function(key, value) {
    			$('#ranking_category').append($("<option></option>").attr("value",value).text(value));
    		});
    		$('#ranking_category option').each(function(){
    			if ($(this).val() == $_GET['ranking_category']) {
    				$(this).attr("selected","selected");
    			}
    		});
    	} else {
    		$('#ranking_category').append($("<option></option>").attr("value",'all').text('All')); 
    	}
    }
    
    $('.trigger_change_rankings').change(function(){
    	triggerRankings();
    });
    
    
    $('div.p3_div').hover(function(){$(this).addClass('hover');},function(){$(this).removeClass('hover');});
    $('div.p3_div').each(function(){
        if ($(this).find('span.p3c').height() > 190) {
            $(this).find('span.clicktoread').show();
            //console.log('k');
        }
    });
    $('span.clicktoread').click(function(){
        if ($(this).hasClass('close')) {
        $(this).parent().css('height',250);
        $(this).removeClass('close');
        $(this).find('b').html('Click to read the full article');
        }else{
        $(this).parent().css('height','auto').css('height',$(this).parent().height()+20);
        $(this).addClass('close');
        $(this).find('b').html('Click to collapse');
        }
        
    });
    $('div.p3_div > div').click(function(){
    	if ($(this).parent().find('span.clicktoread').hasClass('close')) {
    		$(this).parent().css('height',250);
    		$(this).parent().find('span.clicktoread').removeClass('close');
        	$(this).parent().find('span.clicktoread').find('b').html('Click to read the full article');
    	}
    });
    $('h2.toggle').click(function(){
        var o = '#'+$(this).attr("id") + "_c";
        $(o).toggle();
        if ($(this).hasClass('tclose')) {
            $(this).removeClass('tclose');
        } else {
            $(this).addClass('tclose');
        }
    });
    
    
    function pSlider(pSliderPos) {
        if (pSliderNext > pSliderMax-1) {
            pSliderPos = 0; pSliderNext = 0;
        }
        $("div#p_slider ul").animate({ left: -pSliderPos*637 }, {duration: animTime});
        $('a.slider-control').removeClass('active');
        $('a.slider-control[rel='+pSliderPos+']').addClass('active');
        pSliderNext++;
    }
    
    
    // image slider
    if ($('#p_slider').css('display') == 'block') {
        var images = $('#p_slider > ul > li');
        var pSliderPos = 0, animTime = 300, pSliderChange = 8000, pSliderNext = pSliderPos+1, pSliderMax = images.length, indit;
        var iclass = '';
        // dots
        $.each(images,function(index,value) {
            iclass = '';if (index == 0) { iclass=' active';}
            $('#p_slider_dots').append('<a class="slider-control'+iclass+'" rel="'+index+'">'+(index+1)+'</a>');
        });
        
        indit = setInterval(function() { pSlider(pSliderNext); }, pSliderChange);	
    }
    
     
    $('a.slider-control').click(function(){
    	clearInterval(indit);
        $('a.slider-control').removeClass('active');
        pSliderPos = $(this).attr("rel");pSliderNext=pSliderPos+1;
        $(this).addClass('active');
        $("div#p_slider ul").animate({ left: -pSliderPos*637 }, {duration: animTime});
        indit = setInterval(function() { pSlider(pSliderNext); }, pSliderChange);
    });
    
    
    $('#statistics_w div img, #ww_w div img').hover(
        function(){
            // hide all
            $('div.contents').hide();
            $(this).parent().find('div.contents').show();
        },
        function(){
        }
    );
    $('#statistics_w div.close, #ww_w div.close').live('click',function(){
        $(this).parent().hide();
    });
    
    $('#ranking_ppc a').click(function(){
        if ($('#events_div').css("display") == 'block') {
            $('#events_div').hide();
            $('#participations_content').show();
            $(this).find('span').html('Ranking list');
        } else {
            $('#participations_content').hide();   
            $('#events_div').show();     
            $(this).find('span').html('Participation');
        }
    });
    
    /*$('#pic_container h1').each(function(){
        if (!$(this).hasClass('entry-title')) {
            $(this).html('<span>'+$(this).html()+'</span>');
        }
    });*/
    
    
    var newst = 0, newstcurpos = 1;
    $('#newsthm_next').click(function(){
        newst = $('#imagef').width();
        if ((newstcurpos*560)<=newst) {
            $('#imagef').animate({left:'-=560'},200);
            newstcurpos++;
            $('#newsthm_prev').addClass('active');
            if (((newstcurpos+1)*560)<=newst) {
                // van kovetekezo is
                $(this).addClass('active');
            } else {
                $(this).removeClass('active');
            }
        }
    });
    $('#newsthm_prev').click(function(){
        newst = $('#imagef').width();
        if (newstcurpos>1) {
            $('#imagef').animate({left:'+=560'},200);
            newstcurpos--;
            $('#newsthm_next').addClass('active');
            if (newstcurpos>1) {
                $(this).addClass('active');
            } else {
                $(this).removeClass('active');
            }
        }
    });
    
    
    
    //$("a").not("[href*='iwf.net']").not("[href*='verba.hu']").not("[href^=#]").not("[href^=mailto]").attr('target','_blank');
    
});

function printpage(){
    var URL = window.location.href.replace("#","");
    if (URL.indexOf("?") > -1) {
        window.open(URL+'&printpage=1');
    } else {
        window.open(URL+'?printpage=1');
    }
}
