﻿
/*
* Author: Inexes s.r.o. - www.inexes.cz
* Created on: 9.11.2010
* Modified on: 4.1.2011
* SVN revision: 1844
*
* Name: inCMS page initialization functions
* Summary: 
*
* Dependences: jQuery 1.4.4, jQuery.History 1.5.0
*
*/

// Inbox flash variables settings
var InboxFlashVariables = "controlColor=16777215&backgroundColor=0&controlBackground=0&controlsResizeType=smart&controlsPadding=5,5,5,5&autoPlay=true";


// Fce pro vytvoreni bezpecneho odkazu
inCMS.initLinks = function() {
    var mailList = $('span.link');
    mailList.each(function(){
        var mail = $(this).html().replace('(zavinac)','@');
        mail = mail.replace(/\(tecka\)/g,'.');
        $(this).html('<a href="mailto:'+mail+'" title="'+mail+'">' + mail +'</a>');
    });
}
inCMS.initLinks();


// IE6 png image replacing using DD_belatedPNG
if (jQuery.browser.msie && jQuery.browser.version < 7) {
    DD_belatedPNG.fix('#headerBox, #ctl00_LogoLink img, .png, #mainCategoryMenu li a'); // <-- insert here selectors separed with comma ", "
}

$(document).ready(function() {
    
    // list onClick
    $('.listType1 .listItem').each(function() {
        if ($(this).find('.buttonLink').length > 0) {
        
        var href = $(this).find('.buttonLink').attr('href');
        
        $(this).find('.buttonLink').attr('href', 'javascript:void()');
	    $(this).find('.image').attr('href', 'javascript:void()');
	    $(this).click(function() {
            if ($(this).find('.buttonLink').attr('target') == "_blank") {
				window.open(href);
			} else {
				window.location.href = href;
			}
        });
        }
    });
    
    setFocus('.firstFocus');

    // Reformat playMovie structure to valid one accepted by Inbox
    $('a.playMovie').each(function() {
        var link = $(this).attr('href');
        if($(this).hasClass('flv')) { var videoType = "flv"; }else{ var videoType = "swf";}
        var linkContent = this.innerHTML;
        if ($(this).hasClass('hidden')) { var linkHidden = ' hidden'; } else { var linkHidden = ''; }
        var linkTitle = $(this).attr('title');
        var linkRel = $(this).attr('rel');
        var template = $('\
                <div class="item playMovie' + linkHidden + '">  \
                    <div class="image"><a title="' + linkTitle + '" href="' + link + '" rel="' + linkRel + '" class="'+ videoType +'">' + linkContent + '</a></div>  \
                    <div class="description" style="display: none">   \
                        <div class="docLink"><a href="' + link + '" /></div>    \
                    </div>  \
                </div>  \
            ');
        $(this).replaceWith(template);
    });


    setEqualHeightInRow('.list', '.listItem .itemTitle h3', 3);
    setEqualHeightInRow('.list', '.listItem .itemTitle .date', 3);
    setEqualHeightInRow('.list', '.listItem .itemTitle .author', 3);
    setEqualHeightInRow('.list', '.listItem .itemTitle', 3);
    setEqualHeightInRow('.list', '.listItem.woTitle .introText', 3);
    setEqualHeightInRow('.list', '.listItem .listDefault', 3);
    setEqualHeightInRow('.list', '.listItem', 3);


    //if ($('h1:first').html() == '') { $('h1:first').remove(); }

    // Reformat infozone modules into panes
    reformatInfozoneModulesIntoPanes();

    function setFocus(element) {
        $(element).focus();
    }

    $('.toggleLogin').click(function() {
        $('#loginBox').slideToggle(500, function() { setFocus('.firstFocus'); });
    });

    /*
    * Test whether argument elements are parents
    * of the first matched element
    * @return boolean
    * @param objs
    * 	a jQuery selector, selection, element, or array of elements
    */
    $.fn.hasParent = function(objs) {
        // ensure that objs is a jQuery array
        objs = $(objs); var found = false;
        $(this[0]).parents().andSelf().each(function() {
            if ($.inArray(this, objs) != -1) {
                found = true;
                return false; // stops the each...
            }
        });
        return found;
    }

    $(document).click(function(event) {
        var target = $(event.target);
        if (target.hasParent('.loginWrap') != true) {
            if (target.hasClass('scrollRight') != true) {
                $('#loginBox').slideUp(500);
            }
        }

    });
    
    $('.gameTable.active tr').click(function(event) {
        $(this).parent().find('tr').removeClass('selected');

        if (!$(event.target).closest("input[type='checkbox']").length) {
            if ($(this).find("input[type='checkbox']:disabled").length == 0) {
                if ($(this).find("input[type='checkbox']:checked").removeAttr('checked').length == 0) {
                    $(this).find('input').attr('checked', 'checked');
                }
            }
        };

        checkAnswerCount();

        $(this).parent().find("tr").find(":checked").parents("tr").addClass('selected');
    });
    
    $('.form').keypress(function(event) {
    
        if (event.which == '13') { 
            $(this).find('.SubmitButton').click();
        }

    });
    
    


    // breadcrumb	
    //	if ($('#menuList-h1 li.active').length > 0) {
    //		$('#menuList-h1 li.active > a').clone().appendTo('.level1');
    //	} else {
    //		$('#menuList-h1 li > a').each(function() {
    //			if ($(this).attr('href') == "/moje-konto/") {
    //				$(this).clone().appendTo('.level1');
    //			}
    //		});
    //	}
    //	$('#menuList-v1 li.open > a').clone().appendTo('.level2');

    //	$('#menuList-v1 li').each(function() {
    //		if ($(this).find('.open').length > 0) { $(this).removeClass('expandable').addClass('collapsable'); $(this).find('ul').show(); }
    //	});

    

    //	$(".gameTable.active tr input[type='checkbox']").click(function() {
    //		$(this).parents('tr').removeClass('selected');
    //		$(this).parents('tr').find(':checked').parents('tr').addClass('selected');
    //	});


    // mainCategoryMenu
    $('#mainCategoryMenu li').each(function(index) {
        $(this).addClass('item' + ++index);
    });

    

    // ItemBox clearing
    $('div > .itemBox:nth-child(3n+1)').addClass('firstInRow');
    $('div > .itemBox:nth-child(3n)').addClass('lastInRow').after('<div class="cleaner" />');

    // Comments separations
    $('.comment').each(function(index) {
        if (index % 2 == 0) $(this).addClass('even');
    });

    // Radio buttons border fix
    $('input[type=radio]').css('border', 'none');
    $('input[type=checkbox]').css('border', 'none');

    // IE6 repair script waiting sequence
    if (jQuery.browser.msie && jQuery.browser.version < 7) {
        waitForIE7 = setInterval(function() {
            if (IE7.loaded) {
                clearInterval(waitForIE7);
                globalInitialization();
            }
        }, 500);
    } else {
        // Run when browser isnt IE
        globalInitialization();
    }

    

    // Hover description initialization
	if ($('#boardHover').size() < 1) {
		$('body').append('<div id="boardHover" style="display:none"></div>');
	}
	var boardHover = $('#boardHover');
	var hideTimeout = false;

	$(boardHover).hover(function() {
		clearTimeout(hideTimeout);
	}, function() {
		clearTimeout(hideTimeout);
		$(boardHover).hide();
		hideTimeout = setTimeout(function() {
			$(boardHover).hide();
		}, 1000);
	});

	$('.board .note').hover(function() {
	        $(boardHover).removeAttr('class');
            $(boardHover).addClass($(this).attr('class'));
			clearTimeout(hideTimeout);			
			var destDesc = $(this).find('.inner');
			if ($(destDesc).find('p').html().length > 0) {
				$(boardHover).html($(destDesc).find('p').html());
				$(boardHover).css({
					top: $(this).offset().top + ($(this).outerHeight(true) / 4),
					left: $(this).offset().left + ($(this).outerWidth(true) / 2)
				});
				$(boardHover).show();
			} else {
				clearTimeout(hideTimeout);
				$(boardHover).hide();
			}
		
	}, function() {
		clearTimeout(hideTimeout);
		hideTimeout = setTimeout(function() {
			$(boardHover).hide();
		}, 100);
	});
	
	
	// Hover gallery
	if ($('#listType1Hover').size() < 1) {
		$('body').append('<div id="listType1Hover" style="display:none"></div>');
	}
	var listType1Hover = $('#listType1Hover');
	var hideTimeout = false;

	$(listType1Hover).hover(function() {
		clearTimeout(hideTimeout);
	}, function() {
		clearTimeout(hideTimeout);
		$(listType1Hover).hide();
		hideTimeout = setTimeout(function() {
			$(listType1Hover).hide();
		}, 1000);
	});

	$('.gallery .item').hover(function() {
	        $(listType1Hover).hide();
	        $(listType1Hover).removeAttr('class');
            $(listType1Hover).addClass($(this).attr('class'));
			clearTimeout(hideTimeout);			
			var destDesc = $(this).find('.introText').html();
			var destDescTrim = $.trim(destDesc);

			if ($(destDescTrim).length > 0) {
				$(listType1Hover).html($(destDesc));
				$(listType1Hover).css({
					top: $(this).offset().top + ($(this).outerHeight(true) / 4),
					left: $(this).offset().left + ($(this).outerWidth(true) / 2)
				});
				$(listType1Hover).show();
			} else {
				clearTimeout(hideTimeout);
				$(listType1Hover).hide();
			}
		
	}, function() {
		clearTimeout(hideTimeout);
		hideTimeout = setTimeout(function() {
			$(listType1Hover).hide();
		}, 0);
	});


});

if($(".counterInfo1").length > 0){
    var topOffset = $(".counterInfo1").offset().top;    
    $(window).scroll(function () {

        if ($(window).scrollTop() >= topOffset){$(".counterInfo1, .counterInfo2").addClass("fixedInfo");  }else{$(".counterInfo1, .counterInfo2").removeClass("fixedInfo");}             

    });
}


	
var listType1 = new Object();

listType1.initialize = function(parentSelector) {


if ($('#listType1Hover').size() < 1) {
		$('body').append('<div id="listType1Hover" style="display:none"></div>');
	}
	var listType1Hover = $('#listType1Hover');
	var hideTimeout = false;

	$(listType1Hover).hover(function() {
		clearTimeout(hideTimeout);
	}, function() {
		clearTimeout(hideTimeout);
		$(listType1Hover).hide();
		hideTimeout = setTimeout(function() {
			$(listType1Hover).hide();
		}, 1000);
	});
	

	$(parentSelector + ' .listItem.wIntroText').hover(function() {
	if (!$(this).hasClass('woTitle')) {
			clearTimeout(hideTimeout);
			$(listType1Hover).children(':not(.bottomArrow)').remove();
			var destDesc = $(this).find('.description');
			if ($(destDesc).find('.introText').html().length > 0) {
				$(listType1Hover).append($(destDesc).clone());
				$(listType1Hover).css({
					top: $(this).offset().top + ($(this).outerHeight(true) / 4),
					left: $(this).offset().left + ($(this).outerWidth(true) / 2)
				});
				$(listType1Hover).show();
				//$(listType1Hover).fadeIn();
			} else {
				clearTimeout(hideTimeout);
				$(listType1Hover).hide();
			}
		}
	}, function() {
		clearTimeout(hideTimeout);
		//$(listType1Hover).hide();
		hideTimeout = setTimeout(function() {
			$(listType1Hover).hide();
		}, 100);
	});
}



$(window).load(function() {

    if ($('#sidePane').outerHeight() >= $('#mainContentBox').outerHeight()) { $('#mainContentBox').css('min-height', parseInt($('#sidePane').outerHeight()) + 'px'); }

    $('.imageContainer').each(function() {
        var wrapWidth = $(this).width();
        var wrapHeight = $(this).height();
        var image = $(this).children('img');
        var imageWidth = $(image).outerWidth();
        var imageHeight = $(image).outerHeight();
        $(image).css({ 'top': (wrapHeight - imageHeight) / 2 + 'px', 'left': (wrapWidth - imageWidth) / 2 + 'px' });
    });
    $('.thumbs a').each(function() {
        var wrapWidth = $(this).width();
        var wrapHeight = $(this).height();
        var image = $(this).children('img');
        var imageWidth = $(image).outerWidth();
        var imageHeight = $(image).outerHeight();
        $(image).css({ 'top': (wrapHeight - imageHeight) / 2 + 'px', 'left': (wrapWidth - imageWidth) / 2 + 'px' });
    });
    $('#largeThumb').each(function() {
        var wrapWidth = $(this).width();
        var wrapHeight = $(this).height();
        var image = $(this).children('img');
        var imageWidth = $(image).outerWidth();
        var imageHeight = $(image).outerHeight();
        $(image).css({ 'top': (wrapHeight - imageHeight) / 2 + 'px', 'left': (wrapWidth - imageWidth) / 2 + 'px' });
    });
});

function globalInitialization() {  

 
    initializePaneSwitching();    


}

/**
 * Pane Switching
 * paneSwitchTo - switch panes by given paneID (without #), links href must contain "#/" before ID
 */
function paneSwitchTo(paneID) {		
		var paneToSwitch = $('.paneWrap .paneHead a[href$="#/' + paneID + '"]'); // find paneHead		
    var paneWrap = $(paneToSwitch).parent().parent(); // find panes parent
    // Mark active paneHead
    $('.paneHead a', paneWrap).removeClass('active');
    $(paneToSwitch).addClass('active');
    // Show actual pane, hide others
    $('.paneBlocks .pane', paneWrap).each(function () {
        if ($(this).attr('id') == paneID) {
            $(this).show();
        } else {
            $(this).hide();
        }
    });
}



/**
 * Pane Switching
 * initializePaneSwitching - initialization
 */
function initializePaneSwitching(){
    var documentTitle = document.title; // save original title for rewrite

    // Bind function to history(location) change event
    $.History.bind(function(state){
        var paneLink = state.substring(1, state.length); // get pane ID
        var paneTitle = $('a[href$="' + state + '"]').text(); // get title
        document.title = documentTitle + " - " + paneTitle;
        // Swith to pane with ID
        paneSwitchTo(paneLink);
    });  
		
		// Remove empty panes
    $('.paneWrap .paneHead a').each(function () {
        var paneLink = $(this).attr('href');
        paneLink = paneLink.substring(paneLink.search("#"));
        paneLink = paneLink.substring(2, paneLink.length);

        if ($('.paneWrap .paneBlocks #' + paneLink).children('*').size() < 1) {
            $(this).remove();
						$('.paneWrap .paneBlocks #' + paneLink).remove();
        }
    });

    // Set default pane (first one)        
    $('.paneWrap').each(function(){
        if($('.paneHead a.active', this).size() < 1){
            $('.paneHead a:first-child', this).addClass('active');
            $('.paneBlocks .pane', this).hide();
            $('.paneBlocks .pane:first-child', this).show();
        }
    });    
    
}


function replaceSpacesWith(selector, replaceString){
    $(selector).each(function(){
        var text = $(this).html();
        $(this).html(text.replace(/ /g, replaceString));
    });
}

function setEqualHeightInRow(parentSelector, childSelector, itemsPerRow){
    $(parentSelector).each(function(){
        var items = $(this).find(childSelector);
        var itemCount = $(items).size();

        // Set equeal height for items in row
        for (var i = 0; i < itemCount; i += itemsPerRow) {
            // Get max height in row
            var actualMaxHeight = 0;
            for (var j = 0; j < itemsPerRow; j++) {
                var height = $(items).eq(i+j).height();
                if(height > actualMaxHeight) actualMaxHeight = height;
            }
            // Set height in row
            for (var j = 0; j < itemsPerRow; j++) {
                $(items).eq(i+j).height(actualMaxHeight);
            }
        }

    });
}

function replaceDiacriticsWithEquivalents(originalString){
    var charsWith =     "áäčďéěíĺľňóôöŕšťúůüýřžÁÄČĎÉĚÍĹĽŇÓÔÖŔŠŤÚŮÜÝŘŽ";
    var charsWithout =  "aacdeeillnooorstuuuyrzAACDEEILLNOOORSTUUUYRZ";
    var convertedString = "";

    for(i=0;i<originalString.length;i++) {
        if (charsWith.indexOf(originalString.charAt(i))!=-1) 
            convertedString+=charsWithout.charAt(charsWith.indexOf(originalString.charAt(i))); 
        else
            convertedString+=originalString.charAt(i);
    }
    
    return convertedString;
}

/**
  *  Reformat infozone modules into panes
  */
function reformatInfozoneModulesIntoPanes() {    
    $('#infoContentBoxContent > .cleaner').remove(); // remove irelevant elements
    var items = 0;
    var infoZoneBox = $('#infoContentBox');
    var infoZonePaneHead = $('.paneWrap .paneHead', infoZoneBox);
    var infoZonePaneHeadCleaner = $('.cleaner', infoZonePaneHead);
    var infoZonePaneBlocks = $('.paneWrap .paneBlocks', infoZoneBox);
    var infoZonePaneBlocksCleaner = $('.cleaner', infoZonePaneBlocks);
    var actualUrl = actualPageURL;

    $('#infoContentBoxContent > div').each(function () {
        items++;
        // Contruct pane title
        var paneTitle = $(this).find('h2');
        if ($(paneTitle).size() < 1) {
            paneTitle = String(items);
        } else {
            paneTitle = $(paneTitle).text();
        }
        // Construct pane head link
        // Replace spaces with "-", diacritic with ASCII and cut off other chars than letters, numbers and "-"
        var paneID = replaceDiacriticsWithEquivalents(paneTitle.replace(/ /g, "-")).replace(/[^A-Za-z0-9-]/g, "");
        var paneHeadElement = '<a href="' + actualUrl + '#/' + paneID + '">' + paneTitle + '</a>';
        $(infoZonePaneHeadCleaner).before(paneHeadElement);
        // Contruct pane block
        $(this).wrap('<div class="pane" id="' + paneID + '" />');
        $(this).parent().insertBefore(infoZonePaneBlocksCleaner);
    });
};




/* jQuery plugins */


/**
* @author Stephane Roucheray 
* @extends jquery
*/

jQuery.fn.iframeResize = function (options) {
    var settings = jQuery.extend({
        width: "fill",
        height: "auto",
        autoUpdate: true
    }, options);
    var filler = 5;

    function onEachIframe() {
        var frame = jQuery(this);
        var body = frame.contents().find("body");

        //frame.css("overflow", "hidden");
        if (settings.autoUpdate) {
            if (jQuery.browser.msie) {
                frame.attr("scrolling", "auto");
                setInterval(immediateResize, 1000);
            }
            else {
                body.bind("DOMSubtreeModified", {
                    frame: frame
                }, resizeIframe);
                body.click(function(){
                    var e = jQuery.Event();
                    e.data = {};
                    e.data.frame = frame;
                    resizeIframe.call(this, e);
                });

            }
        }
        immediateResize();

        function immediateResize() {
            var e = jQuery.Event();
            e.data = {};
            e.data.frame = frame;
            resizeIframe.call(body, e);
        }
    }

    function resizeIframe(event) {
        var body = jQuery(this);
        event.data.frame.css("width", settings.width == "fill" ? "100%" : parseInt(settings.width));
        event.data.frame.css("height", settings.height == "auto" ? body.outerHeight(true) + filler : parseInt(settings.height));        
    }

    jQuery(this).children("iframe").each(onEachIframe);
};
