
/*
 * 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=14811173&controlsResizeType=smart&controlsPadding=5,5,5,5&movieMargin=0,0,32,0&autoPlay=true";
var jScrollApi = false;
var enabledCanvas = false;

// 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'); // <-- insert here selectors separed with comma ", "
}

$(window).load(function () {
    afterContentResize();
});
$(window).resize(function () {
    clearTimeout(delayer);
    var delayer = setTimeout(function () {
        afterContentResize();
    }, 500);
});

$(document).ready(function() {

	// TODO Documentation
	$('.reference:first').addClass('first');
	$('.grayBox:first').addClass('first');

	// Reformat playMovie structure to valid one accepted by Inbox
	$('a.playMovie').each(function() {
		var link = $(this).attr('href');
		var linkContent = this.innerHTML;
		var linkTitle = $(this).attr('title');
		var template = $('\
            <div class="item playMovie">  \
                <div class="image"><a title="' + linkTitle + '" href="' + link + '" rel="lightbox-1_1" class="flv">' + linkContent + '</a></div>  \
                <div class="description">   \
                    <div class="docLink"><a href="' + link + '" /></div>    \
                </div>  \
            </div>  \
        ');
		$(this).replaceWith(template);
	});


	// TODO Documentation
	$('div.reference .playMovie .image > a').each(function() {
		//alert($(this).attr('title'));
	
		var tooltipWidth = $(this).parent().parent().parent().find('.tooltip').html().length * 10;
		$(this).parent().parent().parent().find('.tooltip').css('width', tooltipWidth + 'px');
		//$(this).prepend('<span class="tooltip" style="width: ' + tooltipWidth + 'px">' + $(this).attr('title') + '</span>');
	});
	// TODO Documentation
	$('div.reference .playMovie a, div.reference .icon').hover(function() {
	$(this).parent().parent().parent().find('.tooltip').show();
	}, function() {
	$(this).parent().parent().parent().find('.tooltip').hide();
});

// TODO Documentation old version (references in wysiwyf
$('table.reference .playMovie a, table.reference .icon').each(function() {
	var tooltipWidth = $(this).attr('title').length * 10;
	$(this).prepend('<span class="tooltip" style="width: ' + tooltipWidth + 'px">' + $(this).attr('title') + '</span>');
});
// TODO Documentation
$('table.reference .playMovie a, table.reference .icon').hover(function() {
	$(this).find('.tooltip').show();
}, function() {
	$(this).find('.tooltip').hide();
});

	// Print plugin
	/*$('.buttonPrint').click(function (e) {
	e.preventDefault();
	$("#mainBox #mainContentBox .inner").printElement({ printMode: 'popup' });
	});*/

	// Flash replace with canvas
	enabledCanvas = jQuery.uaMatch(navigator.userAgent).browser == "webkit" ? true : false;
	//enabledCanvas = true;

	// ItemBox Stretching (title, whole block)
	setEqualHeightInRow('.listType2', '.listItem .height h3', 3);

	// Define an element to initialize jScroll on
	var jScrollElement = $('#contentToScroll');
	var jScrollProperties = {
		scrollbarWidth: 13,
		scrollbarMargin: 0,
		animateTo: true,
		wheelSpeed: 30,
		animateInterval: 20,
		animateStep: 2,
		showArrows: true,
		autoReinitialise: false
	};

	var flash = false;

	if (!enabledCanvas) {
		$('#contentToScroll').live('jsp-initialised', function() {
			if (!flash) {
				initialiseFlash();
			}
			return false;
		});
	} else {
		$('#canvasBackground').append('<canvas id="backCanvas" style="position:absolute; top:0; left:0; z-index:0;">No support for canvas!</canvas>');
		setImageBackground();
	}

	function setImageBackground() {
		var firstImage = $('.listType3 .listItem:first .image img').attr('src');
		if (!enabledCanvas) {
			if (flash) {
				if (firstImage) {
					firstImage = firstImage.replace(/width=[0-9]+&/, "");
					firstImage = firstImage.replace(/height=[0-9]+&/, "");
					var flashObj = $('#imageOnBackground')[0];
					if (typeof (flashObj.setImage) == "function") {
						flashObj.setImage(firstImage);
					} else {
						setTimeout(function() {
							setImageBackground();
						}, 100);
					}
				}
			}
		} else {
			var imgCanvas = $('#imgForCanvas');
			if (firstImage) {
				firstImage = firstImage.replace(/width=[0-9]+&/, "");
				firstImage = firstImage.replace(/height=[0-9]+&/, "");
				$(imgCanvas).attr('src', firstImage);
				setCanvasImageBackground();
				// canvas
			}
		}
	}

	function initialiseFlash() {
		var flashHeight = "100%";
		if (window.imageBackgroundType2) {
			flashHeight = "435px";
		}

		swfobject.embedSWF(
            window.imageBackgroundFlashMovie, "imageOnBackground", "100%", flashHeight, "9.0.0", "ExpressInstall.swf",
            window.imageBackgroundFlashVars,
            {
            	scale: "noborder",
            	menu: false,
            	wmode: "transparent",
            	loop: true,
            	allowScriptAccess: "always",
            	allowFullScreen: true
            },
            {}, function(e) {
            	flash = e.success;
            	setImageBackground();
            });
	}

	var jScrollObject = $(jScrollElement).jScrollPane(jScrollProperties);
	jScrollApi = jScrollObject.data('jsp');

	// Scroll top up
	$('.buttonUp').click(function(e) {
		e.preventDefault();
		jScrollApi.scrollToY(0, 'slow');
	});

});

var imageCanvas = new Image();

function setCanvasImageBackground() {
    var canvas = $('#backCanvas')[0];
		var bodyWidth = $('body').width();
    if(canvas.width != bodyWidth){
        canvas.width = bodyWidth;
    }
    if (window.imageBackgroundType2) {
        if(canvas.height != 435){
            canvas.height = 435;
        }
    } else {
        if(canvas.height != inCMS.windowSize().height){
            canvas.height = inCMS.windowSize().height;
        }
    }
    var context = canvas.getContext('2d');
    context.save();
    var image = new Image();
    var newImageSrc = $('#imgForCanvas').attr('src');
    image.onload = function () {
        drawImage();
    };
    image.src = newImageSrc;

    function drawImage(){
        var sImageWidth = image.width ;
        var sImageHeight = image.height;
        var aspectRatio = parseFloat(sImageWidth / sImageHeight);
        var winWidth = parseInt(canvas.width);
        var winHeight = parseInt(canvas.height);
        var winAspect = parseFloat(winWidth / winHeight);
        var imageWidth = 0;
        var imageHeight = 0;
        var imageTop = 0;
        var imageLeft = 0;

        function fitWidth() {
            imageWidth = winWidth;
            imageHeight = parseInt(imageWidth / aspectRatio);
            imageTop = (winHeight - imageHeight) / 2;
        }
        function fitHeight() {
            imageHeight = winHeight;
            imageWidth = parseInt(imageHeight * aspectRatio);
            imageLeft = (winWidth - imageWidth) / 2;
        }

        // Resize to fit window, without keeping aspect
        if (!aspectRatio) {
            imageWidth = winHeight;
            imageHeight = winWidth;
        } // Resize to fit window, keep aspect
        else {
            if (aspectRatio > winAspect) {
                fitHeight();
            }
            else {
                fitWidth();
            }
        }
        context.drawImage(image, imageLeft, imageTop, imageWidth, imageHeight);
        context.save();
    }

}

function afterContentResize() {
    inCMS.windowWidth = inCMS.windowSize().width;
    if(window.imageBackgroundType2){
        inCMS.windowHeight = Math.max(inCMS.windowSize().height, 666);
    } else {
        inCMS.windowHeight = inCMS.windowSize().height;
    }

    console.log(inCMS.windowSize());
    inCMS.setContentSize();
    if (jScrollApi) {
        jScrollApi.reinitialise();
    }
    if (enabledCanvas) setCanvasImageBackground();
}



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;
            var j = 0;
            for (j = 0; j < itemsPerRow; j++) {
                var height = $(items).eq(i + j).height();
                if (height > actualMaxHeight) actualMaxHeight = height;
            }
            // Set height in row
            for (j = 0; j < itemsPerRow; j++) {
                $(items).eq(i + j).height(actualMaxHeight);
            }
        }

    });
}


// Easing equation, borrowed from jQuery easing plugin
// http://gsgd.co.uk/sandbox/jquery/easing/
jQuery.easing.easeOutQuart = function (x, t, b, c, d) {
    return -c * ((t = t / d - 1) * t * t * t - 1) + b;
};



