/* 
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */



window.zenyAdverts = {
    loadAdvertisements: function(){
        $("div.advert").each(function(){
            var pagetype = $(this).attr("pagetype");
            var position = $(this).attr("position");
            var seznam = $(this).attr("seznam");
            var mobile = $(this).attr("mobile");
            var width = $(window).width();

            banner_advert_str = 'S'+seznam+'M'+mobile;
            window_advert_str = 'S'+advert_seznam_io+'M'+(width<advert_mobile_resolution?1:0);
            if(banner_advert_str===window_advert_str){
                window.zenyAdverts.loadAdvertContent($(this), pagetype, position, width);
            }
        });
    },
    loadAdvertContent: function(advert_wrapper, pagetype, position, width){

        $.get("/ajax/getAdvertContent?pagetype="+pagetype+"&position="+position+"&width="+width, function(data){
            data = JSON.parse(data);
            if(data===false){
                return;
            }

            if(data.position_id==1){

                $('.slider-hp-image').css({background: 'transparent'});

            }

            var content = data.url!="" ?
                data.measuring
                + data.p_html_before
                + "<a target='_blank' href='"+data.url+"'>"
                + data.html_before
                + (data.image!="" && data.image!=null ?"<img src='"+data.image+"' alt='' />":"")
                + data.html_after
                + "</a>"
                + data.p_html_after
                :
                data.measuring
                + data.p_html_before
                + data.html_before
                + (data.image!="" && data.image!=null?"<img src='"+data.image+"' alt='' />":"")
                + data.html_after
                + data.p_html_after
            ;


            if(data.position_id==4){
                $(".left-advert-stack").css({marginLeft: -data.width-10});
            }

            if(position=='BRANDING'){
                // FIXME udelat to tak aby se obrazek opkaoval - vysosnout img a predelat na background image
                // var margintop = pagetype=='homepage'? '-233px' : '-200px';
                // $('.pagebranding-wrapper').prepend('<div style="height: 200px;"></div>');
                // $('.advert[position="FULLBRANDING"]').css({marginTop: margintop}).addClass('ad-class');
                // $('.slider_hp_image, .slider_hp_purple').css({background: 'none'});
                // data.body_bg_hexa!=''?
                //     $('body').css({background: data.body_bg_hexa}) : null
                // ;
            }

            $(advert_wrapper).attr("bannerid", data.banner_id).html(content);
        });
    },
    advertisementListeners: function(){
        $("div.advert").click(function(){
            var pagetype = $(this).attr("pagetype");
            var position = $(this).attr("position");
            var banner_id = $(this).attr("bannerid");
            $.ajax({
                data: {pagetype: pagetype, position: position, banner_id: banner_id},
                method: "POST",
                url: "/ajax/advertClick"
            });
        });

        $(window).scroll(function(){
            window.zenyAdverts.advertisementStickyListen();
        });
    },
    advertisementStickyListen: function(){
        var window_top = $(window).scrollTop();
        if($("#sticky-wrapper").length){
            var max_bottom = $("#sticky-wrapper").offset().top + $("#sticky-wrapper").height();
            // var max_bottom = max_bottom;

            $("div.advert.sticky").each(function(){
                if($(this).height() == 0) return;
                if($(this).attr("pagetype")=="testovani-detail" && $(this).attr("position")=="INNER STICKY" ){
                    return false;
                }
                // var reference_banner_top = $(this).offset().top;
                var reference_top = $("#sticky-wrapper").offset().top;
                var reference_bottom = $(this).offset().top+$(this).height();
                var max_top = max_bottom - $(this).height();

                // var visible_top = 0;
                // var sticky_block_exists = $('.article_left_test_winners, .article_left_test_users_in, .test_comments_wrapper').length != 0;
                // if(sticky_block_exists){
                //     $('.article_left_test_winners, .article_left_test_users_in, .test_comments_wrapper').each(function(){
                //         var offset_top = $(this).offset().top + $(this).outerHeight();
                //         if(offset_top > visible_top){
                //             visible_top = offset_top;
                //         }
                //     });
                // }

                // var left_before_sticky = 0;
                // $('.article_left_likes, .test-left-review, .article_left_workroom_events, .article_left_recipe_ingredients, .article_left_exchange_price, .article_left_events, .advert[position=SQUARE_1], .advert[position=SZN_SQUARE]').each(function(){
                //     var offset_top_sticky = $(this).offset().top + $(this).outerHeight();
                //     if(offset_top_sticky > left_before_sticky){
                //         left_before_sticky = offset_top_sticky;
                //     }
                // });

                // if( window_top > left_before_sticky-10 && visible_top+20 > reference_banner_top) {
                //     $(this).attr('style', "display: block; position: fixed; top: "+ (max_top - window_top + 20) +"px;");
                // } else {
                if(window_top + 16 > reference_top){
                    $(this).closest("#sticky-wrapper").attr("style", "min-height: "+ $(this).height()+"px");
                    if(max_bottom < reference_bottom){
                        $(this).attr('style', "display: block; position: fixed; top: "+ (max_top - window_top + 16) +"px; max-width: 300px;");
                    }else{
                        $(this).attr('style', "display: block; position: fixed; top: 20px; max-width: 300px;");
                    }
                } else {
                    $(this).removeAttr('style');
                }
                // }
            });
        }

    }
}









/**
 * Created by tom on 21.09.17.
 */
function fail(message) {
	console.warn(message);
}
function number_format(num, decimals, dec_point, thousands_sep) {

	// default params
	if(decimals === undefined) decimals = 0;
	if(dec_point === undefined) dec_point = ".";
	if(thousands_sep === undefined) thousands_sep = ",";

	// fix decimals
	num = num.toFixed(decimals);

	var m = num.match(/^([\-])?([\d]+)(\.([\d]*))?$/);

	var s = m[1] !== undefined ? "-" : "";
	var i = "";
	var d = m[4] !== undefined ? dec_point+m[4] : "";

	// i
	for(k=1 ; k<=m[2].length ; k++) {
		var index = m[2].length - k;
		var c = m[2][index];
		i = c+i;
		if(k % 3 == 0) i = thousands_sep+i;
	}

	return s+i+d;




}

function numberFormat(number, decimals, thousandSep) {
	if(decimals === undefined) decimals = 2;
	if(thousandSep === undefined) thousandSep = " ";
	return number_format(number, decimals, ",", thousandSep);
}
/**
 * Created by tom on 06.09.17.
 */
window.PHO = {};
/**
 * Created by tom on 20.09.17.
 */
PHO.componentId = function(element) {
	return element.attr("id").replace(/.*\./, "");
};
PHO.convertSQLDate = function(sqlDate) {
	var text = sqlDate.replace(/-/g, "/");
	return new Date(Date.parse(text));
}
/**
 * Created by tom on 06.09.17.
 */
PHO.dispatchEvent = function(name, data) {
	var evt = new CustomEvent(name, {detail: data});
	window.dispatchEvent(evt);
};
PHO.getCookie = function(name) {
	name += "=";
	var decodedCookie = decodeURIComponent(document.cookie);
	var cookies = decodedCookie.split(";");
	for(i in cookies) {
		var cookie = cookies[i];
		while(cookie.charAt(0) == " ") {
			cookie = cookie.substring(1);
		}
		if(cookie.indexOf(name) == 0) {
			return cookie.substring(name.length, cookie.length);
		}
	}
	return "";
};
/**
 * Created by tom on 07.09.17.
 */
PHO.getHashParams = function() {
	var o = {};
	var urlParams = location.hash.substring(1);
	var params = urlParams.split("&");
	for(var i in params) {
		var param = params[i].split("=");
		var key = param[0];
		if(!key.length) continue;
		var value = param.length > 1 ? param[1] : null;
		o[key] = value;
	}
	return o;
};

/**
 * Created by tom on 07.09.17.
 */
PHO.log = function(string) {
	if(PHOData.constants.JS_LOG_ENABLED) console.log(string);
};

/**
 * Created by tom on 18.09.17.
 */
PHO.setCaretPosition = function(el, pos) {

	// Loop through all child nodes
	for(var i in el.childNodes){
		var node = el.childNodes[i];
		if(node.nodeType == 3){ // we have a text node
			if(node.length >= pos){
				// finally add our range
				var range = document.createRange(),
					sel = window.getSelection();
				range.setStart(node,pos);
				range.collapse(true);
				sel.removeAllRanges();
				sel.addRange(range);
				return -1; // we are done
			}else{
				pos -= node.length;
			}
		}else{
			pos = PHO.setCaretPosition(node,pos);
			if(pos == -1){
				return -1; // no need to finish the for loop
			}
		}
	}
	return pos; // needed because of recursion stuff
};
PHO.setCookie = function(name, value, expiration) {
	var d = new Date();
	d.setTime(d.getTime() + (expiration*24*60*60*1000));
	var expires = "expires=" + d.toUTCString();
	var domain = "domain=" + "."+location.host;
	document.cookie = name + "=" + value + ";" + expires + ";" + domain + ";path=/";
};


/**
 * Created by tom on 20.09.17.
 */
String.prototype.dateFormat = function(formatString) {

	var date = this.match(/^([0-9]{4})-([0-9]{2})-([0-9]{2})(\s([0-9]{2}):([0-9]{2}):([0-9]{2}))?$/)

	if(date === null) return false;

	var y = parseInt(date[1]);
	var m = parseInt(date[2]);
	var d = parseInt(date[3]);
	var h = date[5] ? parseInt(date[5]) : 0;
	var i = date[6] ? parseInt(date[6]) : 0;
	var s = date[7] ? parseInt(date[7]) : 0;

	return formatString
		.replace(/j/g, d)
		.replace(/n/g, m)
		.replace(/Y/g, y)
		.replace(/d/g, d < 10 ? "0"+d : d)
		.replace(/m/g, m < 10 ? "0"+m : m)
		.replace(/H/g, h < 10 ? "0"+h : h)
		.replace(/i/g, i < 10 ? "0"+i : i)
		.replace(/s/g, s < 10 ? "0"+s : s);
};

/**
 * Created by tom on 06.09.17.
 */
String.prototype.toCamelCase = function() {
	var camelString = "";
	var state = "s1";
	string = this.split("");
	for(i in string) {

		var ch = string[i];

		switch(state) {
			case "s1" :
				if(ch == "_" || ch == " ") {
					state = "s2";
					break;
				}
				camelString += ch;
				break;
			case "s2" :
				if(ch == "_" || ch == " ") break;
				camelString += ch.toUpperCase();
				state = "s1";
				break;
		}
	}
	return camelString;
}

function compressString(string) {
	return string.trim().replace(/\s+/g, " ");
}
/**
 * Created by tom on 15.09.17.
 */
function count(arr) {
	if(typeof arr === "object") arr = Object.keys(arr);
	return arr.length;
}

function cropLongText(text, charCount, cutter) {

	if(!cutter){
		cutter = "...";
	}
	
	if(text.length <= charCount){
		return text;
	} 
	else {
		var newText = text.substring(0, charCount +1).trim();
		return newText + cutter;
	}
}
/**
 * Created by tom on 20.09.17.
 */
function dateFormat(date, format) {
	return date.dateFormat(format);
}
function doNotEscapeString(string) {
	Template.escapeStrings = false;
	return string;
}
function escapeString(string) {
	string = Template.escapeStrings ? htmlspecialchars(string, 3) : string;
	Template.escapeStrings = true;
	return string;
}
function formatBytes(bytes, precision) {

	if(!precision) precision = 0;

	var units = ["B","KB","MB","GB","TB"];

	bytes = Math.max(bytes, 0);
	var pow = Math.floor((bytes ? Math.log(bytes) : 0) / Math.log(1024));
	pow = Math.min(pow, units.length - 1);

	bytes /= Math.pow(1024, pow);

	var number = bytes.toFixed(precision);
	number = number.replace(".", ",");

	return number + " " + units[pow];
}
function getDayIndex(date) {
	var d = PHO.convertSQLDate(date);
	var index = d.getDay();
	return index > 0 ? index : 7;
}
function getLastMonthDay(year, month) {
	var d = new Date(year, month, 0);
	return d.getDate();
}
function getMonthName(month) {
	switch(parseInt(month)) {
		case  1 : return "leden";
		case  2 : return "únor";
		case  3 : return "březen";
		case  4 : return "duben";
		case  5 : return "květen";
		case  6 : return "červen";
		case  7 : return "červenec";
		case  8 : return "srpen";
		case  9 : return "září";
		case 10 : return "říjen";
		case 11 : return "listopad";
		case 12 : return "prosinec";
	}
	return false;
}
function getPopUp(breakPoint, onScrollElementId, zoneId) {
    //Check if exist cookie with name "cname"
    function getCookie(cname) {
        var name = cname + "=";
        var decodedCookie = decodeURIComponent(document.cookie);
        var ca = decodedCookie.split(';');
        for (var i = 0; i < ca.length; i++) {
            var c = ca[i];
            while (c.charAt(0) == ' ') {
                c = c.substring(1);
            }
            if (c.indexOf(name) == 0) {
                return c.substring(name.length, c.length);
            }
        }
        return "";
    }

    //Set cookie with 30 min expiration
    function setCookie(value) {
        var d = new Date();
        d.setTime(d.getTime() + (30 * 60 * 1000));
        var expires = "expires=" + d.toUTCString();
        document.cookie = "seznam-pop-up-ad-first-look=" + value + ";" + expires + ";path=/";
    }

    //Add necessarily styles to head of page
    function appendStyles() {
        var css = '#seznam-pop-up-ad{ position: fixed; height: 100px; width: 100%; background: rgba(0,0,0,.7);bottom: 0; left: 0; right: 0;  text-align: center; padding: 2px 0; z-index: 1001; transition: height 0.5s; }' +
            '#seznam-pop-up-ad-close{background: rgba(0,0,0,.7); margin-top: -22px; position: absolute; top: 0; right: 0; color: #CCC; cursor: pointer; text-align: center; padding: 0 5px; height: 22px;}' +
            '.seznam-pop-up-ad-hide{ height: 0 !important; padding: 0!important; margin: 0!important;}';
        var style = document.createElement('style');
        style.innerHTML = css;
        document.head.appendChild(style);
    }

    //Create Ad divs
    function createAdDivs() {
        var div = document.createElement('div');
        div.setAttribute('id', 'seznam-pop-up-ad');
        div.innerHTML = ('<div id="seznam-pop-up-ad-close">Zavřít reklamu</div>' + '<div id="ssp-zone-' + zoneId + '" style="margin: 0 auto;"></div>');
        document.body.appendChild(div);
    }

    //Hide Ad
    function hideAd() {
        document.getElementById("seznam-pop-up-ad").classList.add("seznam-pop-up-ad-hide");
        document.getElementById("seznam-pop-up-ad-close").style.display = "none";
    }

    if ( window.innerWidth <= breakPoint && getCookie("SEZNAM") && document.getElementById(onScrollElementId)) {
        if (!getCookie("seznam-pop-up-ad-first-look")){
            setCookie(false);
        }
        appendStyles();
        window.addEventListener("scroll", function () {
            var createdAd = document.getElementById("seznam-pop-up-ad");
            var elementTarget = document.getElementById(onScrollElementId);
            if (window.scrollY > (elementTarget.offsetTop - window.innerHeight)) {
                if (!createdAd && getCookie("seznam-pop-up-ad-first-look") === "false") {
                    setCookie(true);
                    createAdDivs();
                    sssp.getAds([
                        {
                            "zoneId": zoneId,
                            "id": "ssp-zone-" + zoneId,
                            "width": 320,
                            "height": 100
                        }
                    ]);
                }
                if(document.getElementById("seznam-pop-up-ad-close")){

                    document.getElementById("seznam-pop-up-ad-close").addEventListener("click", function () {

                        hideAd();

                    });
                }
            }
        });
    }
}

/**
 * Created by tom on 15.09.17.
 */
function getToday() {
	var now = new Date();

	var Y = now.getFullYear();
	var m = now.getMonth() + 1;
	var d = now.getDate();

	if(m < 10) m = "0"+m;
	if(d < 10) d = "0"+d;

	return Y+"-"+m+"-"+d;
}
function htmlspecialchars(string, quoteStyle, charset, doubleEncode) {
	var optTemp = 0
	var i = 0
	var noquotes = false
	if (typeof quoteStyle === 'undefined' || quoteStyle === null) {
		quoteStyle = 2
	}
	string = string || ''
	string = string.toString()

	if (doubleEncode !== false) {
		// Put this first to avoid double-encoding
		string = string.replace(/&/g, '&amp;')
	}

	string = string
		.replace(/</g, '&lt;')
		.replace(/>/g, '&gt;')

	var OPTS = {
		'ENT_NOQUOTES': 0,
		'ENT_HTML_QUOTE_SINGLE': 1,
		'ENT_HTML_QUOTE_DOUBLE': 2,
		'ENT_COMPAT': 2,
		'ENT_QUOTES': 3,
		'ENT_IGNORE': 4
	}
	if (quoteStyle === 0) {
		noquotes = true
	}
	if (typeof quoteStyle !== 'number') {
		// Allow for a single string or an array of string flags
		quoteStyle = [].concat(quoteStyle)
		for (i = 0; i < quoteStyle.length; i++) {
			// Resolve string input to bitwise e.g. 'ENT_IGNORE' becomes 4
			if (OPTS[quoteStyle[i]] === 0) {
				noquotes = true
			} else if (OPTS[quoteStyle[i]]) {
				optTemp = optTemp | OPTS[quoteStyle[i]]
			}
		}
		quoteStyle = optTemp
	}
	if (quoteStyle & OPTS.ENT_HTML_QUOTE_SINGLE) {
		string = string.replace(/'/g, '&#039;')
	}
	if (!noquotes) {
		string = string.replace(/"/g, '&quot;')
	}

	return string
}
function in_array(needle, haystack) {
	return haystack.indexOf(needle) > -1;
} 
/**
 * Created by tom on 11.09.17.
 */
function loadTemplate(id, tplName) {

	if(!id) {
		console.error("Undefined argument id.");
		return false;
	}

	if(!tplName) {
		console.error("Undefined argument tplName.");
		return false;
	}

	var argv = loadTemplate.arguments;
	var tplParams = [];

	for(i=2 ; i<argv.length ; i++) {
		tplParams.push(argv[i]);
	}

	var node = document.getElementById(id);
	node.innerHTML = '<div id="'+tplName+'" class="placeholder"></div>';


	if(!PHOTemplates[tplName]) {
		var ajax = new Ajax({url: "/pho-ajax/load-template", data: {tplName: tplName}, params: {id: id, tplName: tplName, tplParams: tplParams}, ok: Templates.loaded});
		ajax.send();
	} else {
		var template = new Template(tplName, tplParams);
		template.render();
	}
}
/**
 * Created by tom on 30.08.17.
 */
window.render = function(id) {
	// FIXME IE fix - seznamacke reklamy rozbijely obecne pole - pridavaly Array.prototype.find - tu funkci find pak IE bralo jako polozku jakehokoliv pole
	var ua = window.navigator.userAgent;
	var isIE = /MSIE|Trident/.test(ua);
	if(isIE && Array.prototype.find) {
		delete Array.prototype.find;
	}
	if(!id) {
		var keys = Object.keys(PHOTemplates);
		id = keys[0];
	}
	var argv = render.arguments;
	var tplParams = [];

	for(i=1 ; i<argv.length ; i++) {
		tplParams.push(argv[i]);
	}
	var template = new Template(id, tplParams, false);
	template.render();
};

function twoDigitsNumber(number) {
	return ("0" + number).slice(-2);
}
/**
 * Created by tom on 15.09.17.
 */
function v(variable) {
	console.log(variable);
	return JSON.stringify(variable);
}


