
///////////////////////////////////////
// A4U core js
// Author: Viktors Žarčinskis
///////////////////////////////////////

// Startup params
var mobile = 0;
var mobileWidth = 800;
// EOF :: Startup params

//-------------------------------------------------------------------------------------------------------------------------------

// AJAX functionality
jQuery(document).ready(function(){
	$.ajaxSetup({
		timeout:60000,
		error:function(x,e){
			$("#whitehider").hide();
			if(x.status==0){
				// previous used as problem with connection, but also triggered, when request is cancelled
			}else if(x.status==404 || x.status==500 || x.status==502){
				set("a4u-content", x.responseText, 1);
			}else if(x.status==500){
			}else if(e=='timeout'){
			}else { //502 gateway timeout
			}
		}
	});
});

function load(q, id, woAddressBarChange){
	if(!id){ id="a4u-content"; }
	if( q.substr(0,1) == '?' ){ q = q.substr(1) }
	else if( q.substr(0,2) == '/?' ){ q = q.substr(2) }
	if(mobile && id=='dialog'){ return true }
	
	switch (id){
		case "dialog":
			$("#dialog").empty();
			woAddressBarChange = 1
			$("#dialog").html('<div style="text-align:center; margin-top:50px; margin-bottom: 50px"><img src="/style/images/loading.gif"></div>');
			$("#dialog").dialog({ width: 670, modal: true, show: 'fade', hide: 'fade', title: '' });
		break;
		case "a4u-content":
			$("#a4u-content").animate({opacity: 0.5 }, 2000);
		break;
	}
	
	if(woAddressBarChange==undefined){
		var lnk = q;
		if(shortLink==0) lnk = '?' + lnk;
		window.history.pushState({ id: 345 }, 'Title', lnk);

		if( typeof gtag != "undefined"){
			gtag('config', dataLayer[1][1], {
			  'page_path': lnk
			});
		} else if( typeof ga != "undefined"){
			ga('send', 'pageview',  lnk);
		} else if( typeof _gaq != "undefined"){
			_gaq.push(['_trackPageview']);
		}
		// pixel do this automatically :)
	}
	
	var getlink = "/ajax.php?q="+q;
	if(shortLink==1) getlink = "/ajax.php?"+q;

	$.get(getlink,"",function(data){ set(id, data, woAddressBarChange); });

	// highlight links
	if( $('.group').length ){
		$('a[href="' + q + '"]').closest('.group').find('a').each(function(){
			$(this).removeClass("active");
			$(this).parent().removeClass("active");
		})
	} else {
		$('a').removeClass('active');
		$('a').parent().removeClass('active');
	}

	$('a[href="' + q + '"]').addClass('active');
	$('a[href="' + q + '"]').parent().addClass('active');

	$(".navbar .dropdown-menu.show").removeClass('show');
	$(".navbar-collapse.collapse.show").removeClass('show');
	
	return false;
}

function set(id, data, runJs){
	if( $("#" + id ).is("input") || $("#" + id ).is("select") ){
		$("#"+ id).val( data );
	} else {
		$("#"+ id).html( data );
	}
	
	if( id=="a4u-content" ){
		$("#a4u-content").stop();
		$("#a4u-content").css({opacity: 1});
		setTimeout('$("#a4u-content").css({opacity: 1})',1000);
	}

	if( runJs==undefined || runJs==1){ runCustomJs('load'); }
}

window.onpopstate = function (e) {
	q = document.location.search;
	p = document.location.pathname;
	if(p){
		load(document.location.pathname, 0, 1);
	} else if(q){
		if(document.location.pathname=="/"){
			q = document.location.search;
			// for server wo rewrite
			if( q.substr(0,3) == '?q=' )
				q = q.substr(3);
		
			load(q, 0, 1);
			
		} else {
			// for servers with rewrite beautiful links
			load(document.location.pathname, 0, 1);
		}
	}
};

// EOF :: AJAX functionality

//-------------------------------------------------------------------------------------------------------------------------------

// Custom user JS functionality
function runCustomJs(e){
	pluginJs(e);
}

$( document ).ready( function() { runCustomJs('load'); });
$( window ).resize( function() { runCustomJs('resize') });

pluginJsFunctions = [];
function pluginJs( e ){
	for(nr in pluginJsFunctions[e]){
		var fname  =pluginJsFunctions[e][nr];
		eval(fname);
	}
}

function addCustomJs( fname, when ){
	if( pluginJsFunctions[when] == undefined)
		pluginJsFunctions[when] = [];
	pluginJsFunctions[when].push(fname);
}
// EOF :: Custom user JS functionality

//-------------------------------------------------------------------------------------------------------------------------------

// URL management
function getUrlToArray(url){
	var urlparams = {};
	url.replace(
	    new RegExp("([^?=&]+)(=([^&]*))?", "g"),
	    function($0, $1, $2, $3) { urlparams[$1] = $3; }
	);
	return urlparams;
}

function urlParam(url, param){
	params = getUrlToArray(url);
	var ret = params[param];
	if(ret==undefined){
		if(param in params){ return ''; }
	}
	return params[param];
}

function arrayToGetUrl(array){
	var i = 0;
	var url = '';
	var justQuerie = 0;
	for(key in array){
		var val = array[key];

		if(i==0 && val!=undefined){ justQuerie = 1; }

		var urlVal = encodeURIComponent(val);

		var delim = '&';

		if(justQuerie){
			if(i==0){ delim = "?" }
			else if(i==1){ delim = "&" }
		} else {
			if(i==0){ delim = "" }
			else if(i==1){ delim = "?" }
		}

		if(val==undefined){
			url = url + delim + key;
		} else {
			url = url + delim + key + "=" + urlVal;
		}
		
		i = i + 1;
	}
	console.log(url);
	return url;
}

function updateUri(uri, key, value) {
	var re = new RegExp("([?&])" + key + "=.*?(&|$)", "i");
	var separator = uri.indexOf('?') !== -1 ? "&" : "?";
	if(value==undefined){
		if (uri.match(re)) {
			return uri.replace(re, '$1' + key + '$2');
		} else {
			return uri + separator + key ;
		}
	} else {
		if (uri.match(re)) {
			return uri.replace(re, '$1' + key + "=" + value + '$2');
		} else {
			return uri + separator + key + "=" + value;
		}
	}
}
// EOF :: URL management

//-------------------------------------------------------------------------------------------------------------------------------

// Misc
function defMobile(){
	if( $(document).width() < mobileWidth ) mobile = 1;
	else mobile = 0;
}

addCustomJs('defMobile()','load');
addCustomJs('defMobile()','resize');


// EOF :: Misc

//-------------------------------------------------------------------------------------------------------------------------------

// Aliases
function log(x){ console.log(x) }
// EOF :: Aliases

// Live Edit
function liveEdit(){
	$(".a4uLiveEditPen").remove();
	$(".a4uLiveEditArea").remove();
	liveEditGo();
	setTimeout('liveEditGo()',500);
	setTimeout('liveEditGo()',1000);
}
addCustomJs('liveEdit()','load');

function liveEditGo($str){
	if(window.le2!=undefined)
	$.each(le2, function( index, val ) {
		var value = '|≡' + val + '≡|';

		// plain html
		var obj = $(":contains('" + value + "')").last();
		var html = $(obj).html();
		if(html!=undefined){
			html = html.replace(value,'');
			$(obj).html(html);
			liveEditAddButton(obj,val);
		}

		var obj = $("[placeholder*='" + value + "']").last();
		var html = $(obj).attr('placeholder');
		if(html!=undefined){
			html = html.replace(value,'')
			$(obj).attr('placeholder',html);
			liveEditAddButton(obj,val);
		}
	});
}
var leCooOpen = new Array();
var leCooOpenVal = new Array();
function liveEditAddButton(obj,val){
	var top = $(obj).offset().top-15;
	var left = $(obj).offset().left-15;
	top = Math.floor(top);
	left = Math.floor(left);
	if( $('.a4uLiveEditPen' + top +'x' + left).html()!=undefined ){
		leCooOpen[((top*1)+15)+'_'+((left*1)+15)]=obj;
		leCooOpenVal[((top*1)+15)+'_'+((left*1)+15)]=val;
		return false;
	}
	var button = $('<div class="a4uLiveEditPen a4uLiveEditPen' + top +'x' + left + '"><span class="glyphicon glyphicon-pencil" style="font-size: 12px"></span></div>');
	button.css({ position: 'absolute', top: 0, left: 0});
	button.css({ cursor: 'pointer', opacity: 0.2, border: '1px solid #000', borderRadius: '100%', padding: 5});
	button.css({ background: '#fff', boxShadow: '#999 1px 1px 1px'});
	button.animate({ top: top, left: left},250);

	setTimeout( function(){ 
    	var top = $(obj).offset().top-15;
		var left = $(obj).offset().left-15;
		button.animate({ top: top, left: left},250);
  	}, 1000 );

	setTimeout( function(){ 
    	var top = $(obj).offset().top-15;
		var left = $(obj).offset().left-15;
		button.animate({ top: top, left: left},250);
  	}, 2000 );

  	setTimeout( function(){ 
    	var top = $(obj).offset().top-15;
		var left = $(obj).offset().left-15;
		button.animate({ top: top, left: left},250);
  	}, 4000 );

  	$( window ).resize( function() {
		var top = $(obj).offset().top-15;
		var left = $(obj).offset().left-15;
		button.animate({ top: top, left: left},250);
	});

	$('body').append(button);
	button.mouseover(function(){
		$(this).css({ opacity: 1 });
		var leID = $(this).attr('data-leID');
		$(obj).css("background","rgba(255,255,0,0.5)");
	});
	button.mouseout(function(){
		$(this).css({ opacity: 0.2 });
		$(obj).css("background","none");
	});
	button.click(function(){
		if( $('.a4uLiveEditArea').html()!=undefined ){
			$('.a4uLiveEditArea').remove();
		} else {
			liveEditOpenFrame(obj, val);
		}
	});
}

function liveEditOpenFrame(obj, val, checkMore, mtop){
	if(checkMore==undefined) checkMore=1;
	if(mtop==undefined) mtop=0;

	var top = $(obj).offset().top;
	var left = $(obj).offset().left;
	top = Math.floor(top);
	left = Math.floor(left);

	var module = $(obj).attr('data-module');
	var width = $(obj).width();
	var height = $(obj).height();
	var minHeight = 40;
	var minWidth = 360;
	if( val.substr(0,15)=='webPage/content' && val.substr(-4,4)=='text' ){
		minHeight = 300; height = height + 75;
	} else if( val.substr(0,15)=='webPage/content' && val.substr(-7,7)=='subject' ){
		minHeight = 40; height = 40;
	} else if( val.substr(0,17)=='webPage/languages' ){
		minHeight = 40; height = 40;
	}
	//log( val );
	if(width<minWidth) width=minWidth;
	if(height<minHeight) height=minHeight;

	if(checkMore && leCooOpen[top+'_'+left]!=undefined){
		var id = top+'_'+left;
		liveEditOpenFrame(leCooOpen[id], leCooOpenVal[id], 0, height);
	}
	top = top+mtop;

	var area = $('<iframe frameborder=0 class="a4uLiveEditArea" src="' + editServer + '/?liveEdit&req=' + encodeURIComponent(val) + '&width=' + width + '&height=' + height + '"></iframe>');
	area.css({ position: 'absolute', top: top, left: left});
	area.css({ background: '#eee', border: '1px solid #999', minWidth: minWidth, minHeight: minHeight});
	area.css({ width: width, height: height });
	area.css({ borderRadius: 10, boxShadow: '#999 1px 1px 1px'});
	$("body").append(area);
}
// EOF :: Live Edit



/* a4u shop */
function a4u_addToCart(itemID, count, elem){ //elem needed if slideshow chreate multiple prodToCart elements
	if(count == undefined) count = 1;
	var url = "/ajax.php?a4u-shoppingCart=" + itemID + "&add=" + count;
	$.getJSON(url, function(data){
		$(".a4u_cartSumPlace").html(data.sum);
		$(".a4u_cartCountPlace").html(data.count);
	})
	
	if( $('.prodToCartElem' + itemID).length ){
		$('body').append( '<div id="addTmp">' + $('.prodToCartElem' + itemID)[0].outerHTML + '</div>' );
		var o = $('.prodToCartElem' + itemID);
		if( elem!=undefined ){ o = $(elem).closest('.prodToCartElem' + itemID) }
		$('#addTmp').css({ position: 'absolute', zIndex: 1000, width: o.width(), top: o.offset().top, left: o.offset().left, overflow: 'hidden' })
		var n = $('.a4u_cartSumPlace:visible');
		if( n.length==0 ) n = $('body');
		$('#addTmp').animate({ top: n.offset().top, left: n.offset().left, opacity: 0, width: 50, height: 50 }, 300);
		setTimeout("$('#addTmp').remove();",300);
	}
}

function a4u_changeCount(itemID, count){
	console.log(count);
	var obj = '#a4u-eshopProdCount' + itemID;
	var cnt = $(obj).html()*1;
	if( $(obj).is('input') ){
		cnt = $(obj).val()*1
	}

	if(count=='+'){
		console.log('+');
		cnt = cnt + 1;
	} else if(count=='-'){
		console.log('-');
		cnt = cnt - 1;
	} else {
		cnt = count;
	}

	if( $(obj).attr('min') ) var min = $(obj).attr('min')*1;
	else min = 1;

	if( $(obj).attr('step') ) var step = $(obj).attr('step')*1;
	else step = 1;

	if(cnt<min && count!=0){ cnt = min; }
	else if(cnt%step!=0){ cnt = Math.round(cnt/step) * step; }

	if( $(obj).is('input') ){
		$(obj).val(cnt);
	} else {
		$(obj).html(cnt);
	}

	var url = "/ajax.php?a4u-shoppingCart=" + itemID + "&cnt=" + cnt;
    $.getJSON(url, function(data){
    	$(".a4u_cartSumPlace").html(data.sum);
		$(".a4u_cartCountPlace").html(data.count);
		$(".a4u-productSum" + itemID).html(data.itemSum);
    	if( $(obj).is('input') ){
			$(obj).val(cnt);
		} else {
			$(obj).html(cnt);
		}
    	//, 'cartSum', 1
    });


    return false;

		//var x = $(this).closest('.cartProduct').find('input[name=count]'); $(x).val( $(x).val()*1+1 ); x.change()
		//fixcount(this);
        //var psum = {{$item->price}}*$(this).val();
        //$(`.productSum{{$item->ID}}`).html( psum + ' eur' )
        //$(this).closest('.cartProduct').find('.count-detail span').html( $(this).val() );
}

function fixcount(obj){
	if( $(obj).attr('min') ) var min = $(obj).attr('min')*1;
	else min = 1;
	if( $(obj).attr('step') ) var step = $(obj).attr('step')*1;
	else step = 1;
	var val = $(obj).val()*1;

	if(val<min){ $(obj).val(min); console.log("x") }
	else if(val%step!=0){ val = Math.round(val/step) * step; $(obj).val(val); console.log("y") }
}
/* eof a4u shop */