/**
 * File customizer_admin.js.
 * Theme Customizer Preview extensions.
 */

(function($) {
	// $(document).on('ready', function() {
	$(function() {
		// init js
		previewer.setup();
	});
})(jQuery);

var previewer = new function() {

	this.setup = function() {
		// init customizer preview
		this.addMods();
		this.addDependencies();
	}

	//
	// bindings
	this.addBindings = function() {
		
		wp.customize.bind( 'preview-ready', function() {
			// console.log("previewer ready ...");
			// remove visual customizer shortcuts
			wp.customize.selectiveRefresh.Partial.prototype.createEditShortcutForPlacement = function() {};
			// bindings
			wp.customize.preview.bind( 'hover', function( data ) {
				previewer.hoverMenu("main", data);
			} );
			wp.customize.preview.bind( 'hovermeta', function( data ) {
				previewer.hoverMenu("meta", data);
			} );
			wp.customize.preview.bind( 'hoverdrop', function( data ) {
				previewer.hoverDrop(data);
			} );
			wp.customize.preview.bind( 'scroll', function( data ) {
				// alert(data);
				if (data) { 
					if (data == 'top') nav.scrollTop();
					else nav.scrollDown(data);
				}
			} );
			// check for open section in the Customizer
			wp.customize.preview.send('checksection', true);
		} );

	}
    this.addBindings();

	this.hoverMenu = function(menu, data) {
		// get menu data
		var menu_id = '#'+menu+'menu';
		var menu_style = '';
		if (wp.customize('enable_headerconcept').get()) {
			if (menu == "main") {
				menu_style = wp.customize('navi_header_off_type').get();
			}
			else if (menu == "meta") {
				menu_style = wp.customize('navi_header_sec_off_type').get();
			}
		}
		else {
			if (menu == "main") {
				menu_style = wp.customize('navi_style').get();
			}
			else if (menu == "meta") {
				menu_style = wp.customize('meta_navi_style').get();
			}
		}
		// trigger dropdown menu
		if (menu_style == 'dropdown') {
			previewer.hoverDrop(data);
		}
		else {
			// search submenu
			var done = false;
			$(menu_id+' .menu').children().each(function() {
				//console.log($(this));
				if (!done && $(this).hasClass('menu-item-has-children')) {
					done = this;
				}
			} );
			if (menu_style != 'hover' && menu_style != 'none') {
				// trigger offmenu
				if (data) {
					if (!done) {
						// console.log("open menu from burger");
						if ($(menu_id+' #dropmenu_all').length > 0) {
							$(menu_id+' #dropmenu_all').trigger("click");
						}
					}
					else {
						// console.log("open menu from item");
						nav.openMenu(menu_id, menu, done.id);
					}
				}
				else nav.closeMenus();
			}
			else {
				if (done != false) {
					// trigger normal menu hover
					if (data) {
						$(done).addClass( "hover" );
						$(done).children(0).addClass( "hover" );
					}
					else {
						$(done).removeClass( "hover" );
						$(done).children(0).removeClass( "hover" );
					}
				}
			}
		}
	}
	
	this.hoverDrop = function(data) {
		// console.log("show dropdown ...");
		var preview = '.dropmenu_content.template';
		if ($('.dropmenu_content.submenu').length > 0)
			preview = '.dropmenu_content.submenu';
		if ($('#dropmenu_all_content').length > 0)
			preview = '#dropmenu_all_content';
		
		// trigger dropmenu
		if (data) {
			$(preview).first().addClass('preview');
			$(preview).first().show();
			// nav.resizeDropmenu();
			// nav.positionDropmenu();
		}
		else {
			$(preview).removeClass('preview');
			$(preview).first().hide();
		}
	}

	//
	// mods
	this.addMods = function() {

		// wire custom mods
		wp.customize( 'scrollspeed', function( v ) {
			v.bind( function( newval ) {
				// set speed mod
				$('.navigation').data('mod-scrollspeed', newval);
			} );
		} );
		wp.customize( 'anim', function( v ) {
			v.bind( function( newval ) {
				// set speed mod
				$('.navigation').data('mod-anim', newval);
			} );
		} );
		wp.customize( 'header_scroll_on', function( v ) {
			v.bind( function( newval ) {
				// set speed mod
				$('.navigation').data('mod-header_scroll_on', newval);
			} );
		} );
		wp.customize( 'header_scroll_off', function( v ) {
			v.bind( function( newval ) {
				// set speed mod
				$('.navigation').data('mod-header_scroll_off', newval);
			} );
		} );
		
		// wire header 2.0
		wp.customize( 'navi_header_scroll_on', function( v ) {
			v.bind( function( newval ) {
				// set speed mod
				$('.navigation').data('mod-header_scroll_on', newval);
			} );
		} );
		wp.customize( 'navi_header_scroll_off', function( v ) {
			v.bind( function( newval ) {
				// set speed mod
				$('.navigation').data('mod-header_scroll_off', newval);
			} );
		} );

		wp.customize( 'drop_anim', function( v ) {
			v.bind( function( newval ) {
				$('.dropmenu_wrapper').data('effect', newval);
			} );
		} );
		wp.customize( 'drop_tab_style', function( v ) {
			v.bind( function( newval ) {
				$('.dropmenu_content > .dropmenu_tab').removeClass('triangle triangle_rd circle square square_rd');
				$('.dropmenu_content > .dropmenu_tab').addClass(newval);
				// nav.resizeDropmenu();
			} );
		} );
		wp.customize( 'drop_tab_width', function( v ) {
			v.bind( function( newval ) {
				// nav.resizeDropmenu();
			} );
		} );
		wp.customize( 'drop_row', function( v ) {
			v.bind( function( newval ) {
				if (newval == 'header') newval = wp.customize('branding_row').get();
				else if (newval == 'menu') newval = wp.customize('menu_row').get();
				else if (newval == 'auto') newval = "";
				$('.dropmenu_wrapper').removeClass('row_l row_xl row_xxl row_xxxl');
				$('.dropmenu_wrapper').addClass(newval);
				// nav.resizeDropmenu();
			} );
		} );
		wp.customize( 'drop_align', function( v ) {
			v.bind( function( newval ) {
				$('.dropmenu_wrapper').data('align', newval);
				// nav.resizeDropmenu();
			} );
		} );

		// wire all mods to --vars
		// console.log(shared.mods);
		for (var i=0; i<shared.keys.length; i++) {

			var key = shared.keys[i];
			var value = shared.mods[key];
			// console.log(key, value);

			// sort out non css vars
			if (key.indexOf('--') > -1) {

				// console.log("found mod "+value['mod']+" "+key);
				if (value['type'] == 'fontfamily') {
					wp.customize( value['mod'], function( v ) {
						v.bind( function( newval ) {
                            if (newval != "")
                                newval = previewer.makeGoogleFont(newval);
							var k = shared.getModKey(this.id);
							previewer.setModValue(k, newval);
							previewer.setFontPreview(k, newval);
						} );
					} );
				}
				else if (value['type'] == 'ffselect' ||
						 value['type'] == 'colselect') {
					wp.customize( value['mod'], function( v ) {
						v.bind( function( newval ) {
							var k = shared.getModKey(this.id);
							var nv = wp.customize(newval).get();
							previewer.setModValue(k, nv);
						} );
					} );
				}
				else if (value['type'] == 'shadow') {
					wp.customize( value['mod'], function( v ) {
						v.bind( function( newval ) {
							var k = shared.getModKey(this.id);
							var shadow = previewer.makeShadowValue(newval);
							previewer.setModValue(k, shadow);
						} );
					} );
				}
				else if (value['type'] == 'acolor') {
					wp.customize( value['mod'], function( v ) {
						v.bind( function( newval ) {
                            var k = shared.getModKey(this.id);
							previewer.setModValue(k, newval);
                            previewer.setColorPreview(k, newval);
                            previewer.updateShadows(k);
						} );
					} );
				}
				else {
					wp.customize( value['mod'], function( v ) {
						v.bind( function( newval ) {
							var k = shared.getModKey(this.id);
							var u = shared.mods[k]['unit'];
							if (u == undefined) u = "";
							previewer.setModValue(k, newval + u);
							previewer.setValuePreview(k, newval);
						} );
					} );
				}
			}
		}

    }
    this.makeGoogleFont = function(newval) {
        var tmp = newval.split(':');
        var font = tmp[0];
        if (gfonts[font]) {
            // console.log(font);
            // console.log(gfonts[font]);
            var params = "";
            if (tmp.length > 1) {
                params = ":ital,wght@";
                tmp = tmp[1].split(',');
                var w = []; var it = [];
                for (var i=0; i<tmp.length; i++) {
                    if (tmp[i].indexOf('italic') > -1) 
                        it.push(tmp[i].replace('italic', ''))
                    else 
                        w.push(tmp[i]);
                }
                if (w.length > 0) {
                    for (var i=0; i<w.length; i++) w[i] = "0,"+w[i];
                    params += w.join(';');
                }
                if (it.length > 0) {
                    for (var i=0; i<it.length; i++) it[i] = "1,"+it[i];
                    if (w.length > 0) params += ';';
                    params += it.join(';');
                }
                // console.log(params);
            }
            newval = font;
            font = font.split(' ').join('+');
            var id = 'gfont_'+font+'-css';
            // console.log(id);
            if (document.getElementById(id) != null) {
                var oldfont = document.getElementById(id);
                oldfont.parentNode.removeChild(oldfont);
            }
            link = document.createElement('link');
            link.id = id;
            link.href = 'https://fonts.googleapis.com/css2?family='+font+params;
            link.rel = 'stylesheet';
            document.getElementsByTagName('head')[0].appendChild(link);
        }
		return newval;
    }
	this.makeShadowValue = function(newval) {
        // calculate box-shadow color
        var shadow = newval.split('+').join(' ');
        // console.log(shadow);
		if (shadow != 'none' && shadow.indexOf('color') > -1) {
			var tmp = shadow.split('color');
			shadow = tmp[0];
			tmp = tmp[1].split(' ');
			var sdw = {
				'color': shared.mods['--color'+tmp[0]]['value'],
				'opacity': tmp[1],
			};
			var color = shared.hex2rgb(sdw['color']);
			if (color) {
				color.a = sdw['opacity'] / 100.0;
			}
			else {
				if (sdw['color'] == 'transparent') color = { r:0, g:0, b:0, a:0 };
				else color = shared.rgb2rgba(sdw['color']);
				color.a = (color.a * (sdw['opacity'] / 100.0)).toFixed(2);
			}
			shadow += ' rgba('+color.r+','+color.g+','+color.b+','+color.a+')';
		}
		return shadow;
    }
    this.updateShadows = function(key) {
        // console.log('update shadows ....');
        var col = key.replace('--', '');
        for (var i=0; i<shared.keys.length; i++) {	
            var skey = shared.keys[i];
            var svalue = shared.mods[skey];
            // check for default var
            if (svalue['type'] == 'shadow' && svalue['value'] != 'none') {
                var sdw = wp.customize(svalue['mod']).get();
                if (sdw.indexOf(col) > 0) {
                    // console.log('updating ...');
                    var shadow = previewer.makeShadowValue(sdw);
                    previewer.setModValue(skey, shadow);
                }
            }
        }
    }

	this.setModValue = function(k, v) {
		// console.log("set preview value ...");
		// set value
		document.documentElement.style.setProperty(k, v);
        shared.mods[k]['value'] = v;
		// set defaults
		for (var i=0; i<shared.keys.length; i++) {	
			var key = shared.keys[i];
			var value = shared.mods[key];
			// check for default var
			if (value['default'] == k) {
				// check for dependency
				if (value['dependency'] != undefined && !this.setDependency(v, value['dependency']) ) {
                    document.documentElement.style.setProperty(key, v);
                    shared.mods[key]['value'] = v;
                }
			}
		}
	}
	this.setFontPreview = function(k, v) {
		// console.log(k+" "+v);
		if (k == "--fontFamily1") {
			if (v == "") {
				$('#branding_typo1_wrap .branding_typo1').css('display', 'none');
				$('#branding_typo1_name').html(previewer_wordings.nothing);
			}
			else {
				$('#branding_typo1_wrap .branding_typo1').css('display', 'block');
				$('#branding_typo1_name').html(v);
			}
		}
		if (k == "--fontFamily2") {
			if (v == "") {
				$('#branding_typo2_wrap .branding_typo2').css('display', 'none');
				$('#branding_typo2_name').html(previewer_wordings.nothing);
			}
			else {
				$('#branding_typo2_wrap .branding_typo2').css('display', 'block');
				$('#branding_typo2_name').html(v);
			}
		}
		if (k == "--fontFamily3") {
			if (v == "") {
				$('#branding_typo3_wrap .branding_typo3').css('display', 'none');
				$('#branding_typo3_name').html(previewer_wordings.nothing);
			}
			else {
				$('#branding_typo3_wrap .branding_typo3').css('display', 'block');
				$('#branding_typo3_name').html(v);
			}
		}
	}
	this.setColorPreview = function(k, v) {
		// console.log(k+" "+v);
        var _k = k.replace('--','');
		$('.branding_colors .branding_color.'+_k).find('.color_code').html(v);
	}
	this.setValuePreview = function (k,v) {
        var _k = k.replace('--','');
        
        // replace list-style wording
        if (_k.indexOf('UlistStyle') !== -1) {
            var find = ['disc', 'circle', 'square', 'none'];
            var replace = [
                previewer_wordings.disc, 
                previewer_wordings.circle, 
                previewer_wordings.square, 
                previewer_wordings.no_symbol
            ];
            for (var i = 0; i < find.length; i++) {
                if (v === find[i]) v = replace[i];
            }
        } else if (_k.indexOf('OlistStyle') !== -1) {
            var find = ['decimal', 'decimal-leading-zero', 'lower-roman', 'upper-roman', 'lower-greek', 'armenian', 'georgian', 'lower-alpha', 'upper-alpha', 'none'];
            var replace = [
                previewer_wordings.decimal, 
                previewer_wordings.decimal_leading_zero, 
                previewer_wordings.lower_roman, 
                previewer_wordings.upper_roman, 
                previewer_wordings.lower_greek, 
                previewer_wordings.armenian, 
                previewer_wordings.georgian, 
                previewer_wordings.lower_alpha, 
                previewer_wordings.upper_alpha, 
                previewer_wordings.no_num
            ];
            for (var i = 0; i < find.length; i++) {
                if (v === find[i]) v = replace[i];
            }
        }
        if ($('.value_preview#'+_k).length > 0)
            $('.value_preview#'+_k).html(v);
    }
	
	//
	// dependencies
	this.addDependencies = function() {
		// search dependencies
		var dependencies = shared.getDependencies();
		// console.log(dependencies);
		// wire dependencies
		for (var mod of Object.keys(dependencies)) {
			dependencies[mod]['type'] = shared.getModField(mod, 'type');
			wp.customize( mod, function( value ) {
				value.bind( function( newval ) {
					//console.log(value.id);
					previewer.setDependencies(newval, dependencies[value.id]);
				} );
			} );

		}
	}
	this.setDependencies = function(value, dependencies) {
		// console.log(value);
		// console.log(dependencies);
		for (var i=0; i<dependencies.length; i++) {
			var mod = dependencies[i]['mod'];
			var dependency = dependencies[i]['dependency'];
			var display = this.setDependency(value, dependency);

			if (display) this.setDependentMod(mod);
			else this.resetDependentMod(mod);
		}

	}
	this.setDependency = function(value, dependency) {
		var display = false;
		// old dependency style (single element without value)
		if (typeof dependency === 'string' ) {
			display = shared.calcDependency(value, { 'element': dependency, 'not_value': "" });
		}
		// single dependency
		else if (dependency['element'] != undefined) {
			display = shared.calcDependency(value, dependency);
		}
		// multi dependency
		else {
			var hits = 0;
			var count = 0;
			for (var key of Object.keys(dependency)) {
				if (key != 'operator') {
					var m_dependency = dependency[key];
					var m_element = m_dependency['element'];
					if (typeof m_dependency === 'string' ) m_element = m_dependency;
					// console.log(m_dependency['element']);
					var m_value = wp.customize( m_element ).get();

					var m_display = this.setDependency(m_value, m_dependency);
					if (m_display) hits++;
					count++;
				}
			}
			if (dependency['operator'] == 'and') {
				if (hits == count) display = true;
			}
			else if (dependency['operator'] == 'or') {
				if (hits > 0) display = true;
			}
		}
		return display;
	}
	this.setDependentMod = function(mod) {
		// console.log("set "+mod);
		var key = shared.getModKey(mod);
		var value = shared.mods[key];

		if (value['type'] != 'separator' &&
			value['type'] != 'group' &&
			value['type'] != 'button') {

			var v = wp.customize( value['mod'] ).get();
			if (value['type'] == 'shadow') v = previewer.makeShadowValue(v); 
			var u = value['unit'];
			if (u == undefined) u = "";

			document.documentElement.style.setProperty(key, v+u);
		}
	}
	this.resetDependentMod = function(mod) {
		// console.log("reset "+mod);
		var key = shared.getModKey(mod);
		var value = shared.mods[key];
		
		if (value['type'] != 'separator' &&
			value['type'] != 'group' &&
			value['type'] != 'button') {

			var dv = value['default'];
			if (typeof dv == "string" && dv.indexOf('--') > -1) {
				dv = window.getComputedStyle(document.documentElement).getPropertyValue(dv);
			}
			else {
				var u = value['unit'];
				if (u == undefined) u = "";
				dv += u;
			}
			document.documentElement.style.setProperty(key, dv);
		}
	}
	
}
