﻿
/*
* 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 = "controlsResizeType=smart&controlColor=16777215&backgroundColor=0&controlBackground=1276363&controlsHideTimeout=3&showTime=true&controlsPadding=5,5,5,5";


// 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 () {
	
		
	$('.categoryMenu li').append('<div class="arrow"></div>');
	$('.categoryMenu li a').wrap('<div class="itemWrap" />');
		
    // Reformat infozone modules into panes
    reformatInfozoneModulesIntoPanes();

    // mainCategoryMenu
    $('#mainCategoryMenu li').each(function (index) {
        $(this).addClass('item' + ++index);
    });

    // ItemBox clearing
    $('div > .itemBox:nth-child(2n+1)').addClass('firstInRow');
    $('div > .itemBox:nth-child(2n)').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();
       }

       clearTimeout(delayer);
       var delayer = setTimeout(function() {
       	inCMS.windowWidth = inCMS.windowSize().width;
       	inCMS.windowHeight = inCMS.windowSize().height;
       	inCMS.setContentSize();
       }, 0);


});

$(window).resize(function(){
	clearTimeout(delayer);
	var delayer = setTimeout(function() {
		inCMS.windowWidth = inCMS.windowSize().width;
		inCMS.windowHeight = inCMS.windowSize().height;
		inCMS.setContentSize();
	}, 0);
});

function globalInitialization() {

    // ItemBox Stretching (title, whole block)
    setEqualHeightInRow('#items-catalog', '.itemBox h2 a', 2);
    setEqualHeightInRow('#items-catalog', '.itemBox .info', 2);
    setEqualHeightInRow('#items-catalog', '.itemBox .bottom', 2);

    setEqualHeightInRow('.items-list', '.itemBox h3 a', 2);
    setEqualHeightInRow('.items-list', '.itemBox .info', 2);
    setEqualHeightInRow('.items-list', '.itemBox .bottom', 2);

    // Replace spaces with non-breaking ones
    replaceSpacesWith('table#items-table .price', '&nbsp;')
    replaceSpacesWith('table#items-table .oldPrice', '&nbsp;')


    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 and add number of items to them
    $('.paneWrap .paneHead a').each(function () {
        var paneLink = $(this).attr('href');
        paneLink = paneLink.substring(paneLink.search("#"));
        paneLink = paneLink.substring(2, paneLink.length);

		var paneBlock = $('.paneWrap .paneBlocks #' + paneLink);

		if ($(paneBlock).children('*').size() < 1) {
            $(this).remove();
			$(paneBlock).remove();
		} else {
			var paneID = $(paneBlock).attr('id');
			if (paneID == 'paneComments') {
				var items = $(paneBlock).find('.comment').size();
				if (items > 0) {
					var text = $(this).text();
					$(this).text(text += ' (' + items + ')');
				}
			}


        }
    });

    // 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"); if (settings.autoUpdate) if (jQuery.browser.msie) { frame.attr("scrolling", "auto"); setInterval(immediateResize, 1E3) } 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) };

