jQuery(document).ready(function($){

	sgBeckeendObj = new  beckend();
	sgBeckeendObj.sgInit();
});


function beckend() {

}

beckend.prototype.sgInit =  function() {

	this.imageUpload(); /* It's Image Upload function */
	this.deletePopup(); /* Delete popup */
 	this.titleNotEmpty(); /* Check title is Empty */
 	this.showThemePicture(); /* Show themes pictures */
 	this.showEffects(); /* Show effect type */
 	this.pageAcordion(); /* For page acordion divs */
 	this.fixedPostionSelection(); /* Fuctionality for selected postion */
 	this.showInfo(); /* Show description options */
 	this.opasictyRange(); /* Opcity range */
 	this.subOptionContents();
 	this.addCountris();
 	this.checkedOpenDiv();
  }

beckend.prototype.checkboxAcordion = function(element) {
	if(!element.is(':checked')) {
		element.next("div").css({'display': 'none'});
	}
	else {
		element.next("div").css({'display':'inline-block'});
	}
}

beckend.prototype.imageUpload = function() {
	if(jQuery("#js-upload-image").val()) {
		jQuery(".show-image-contenier").html("");
		jQuery(".show-image-contenier").css({'background-image': 'url("' + jQuery("#js-upload-image").val() + '")'});
	}
	var custom_uploader;
	jQuery('#js-upload-image-button').click(function(e) {
		e.preventDefault();

		/* If the uploader object has already been created, reopen the dialog */
		if (custom_uploader) {
			custom_uploader.open();
			return;
		}
		/* Extend the wp.media object */
		custom_uploader = wp.media.frames.file_frame = wp.media({
			titleFF: 'Choose Image',
			button: {
				text: 'Choose Image'
			},
			multiple: false
		});
		/* When a file is selected, grab the URL and set it as the text field's value */
		custom_uploader.on('select', function() {
			attachment = custom_uploader.state().get('selection').first().toJSON();
			jQuery(".show-image-contenier").css({'background-image': 'url("' + attachment.url + '")'});
			jQuery(".show-image-contenier").html("");
			jQuery('#js-upload-image').val(attachment.url);
		});
		/* Open the uploader dialog */
		custom_uploader.open();
	});

	/* its finish image uploader */
}

beckend.prototype.deletePopup = function() {
	jQuery(".sg-js-delete-link").bind('click',function() {
		var request = confirm("Are you sure?");
		if(!request) {
			return false;
		}
		var popup_id = jQuery(this).attr("data-sg-popup-id");

		var data = {
			action: 'delete_popup',
			popup_id: popup_id
		}

		jQuery.post(ajaxurl, data, function(response,d) {
			//console.log(response);
			location.reload();
		});
	});
}

beckend.prototype.titleNotEmpty = function() {
	jQuery("#add-form").submit(function() {
		var popupTitle = jQuery(".sg-js-popup-title").val();
		if(popupTitle == '' || popupTitle == ' ') {
			alert('Please fill in title field');
			return false;
		}
	});

}

beckend.prototype.showThemePicture = function() {
	jQuery(".popup_theme_name").bind("mouseover",function(e) {
		jQuery('.theme'+jQuery(this).attr("sgpoupnumber")+'').css('display', 'block');
	});
}

beckend.prototype.showEffects = function() {
	effectTimer = '';

	jQuery('select[name="effect"]').bind('change', function() {
		if (effectTimer!='') {
			clearTimeout(effectTimer);
		}
		effectTimer = setTimeout(function() {
			jQuery("#effectShow").hide();
			effectTimer = '';
		},1400);
		jQuery("#effectShow").removeClass();
		jQuery("#effectShow").show();
		jQuery("#effectShow").addClass('sg-animated '+jQuery(this).val()+'');
	});
	jQuery('.js-preview-effect').click(function() {
		if (effectTimer!='') {
			clearTimeout(effectTimer);
		}
		effectTimer = setTimeout(function() {
			jQuery("#effectShow").hide();
			effectTimer = '';
		},1400);
		jQuery("#effectShow").removeClass();
		jQuery("#effectShow").show();
		jQuery("#effectShow").addClass('sg-animated '+jQuery('select[name="effect"] option:selected').val()+'');
	});
}

beckend.prototype.pageAcordion = function() {
	jQuery("#specialoptionsTitle").toggle(function(){
		jQuery('.specialOptionsContent').fadeOut();
		jQuery("#specialoptionsTitle > img").css("transform", 'rotate(0deg)');
	},function(){
		jQuery('.specialOptionsContent').fadeIn();
		jQuery("#specialoptionsTitle > img").css("transform", 'rotate(180deg)');
	});

	function acardionDivs(prama1,param2,param3) {
		jQuery(prama1).toggle(function() {
			jQuery(param2).addClass('closed');
			jQuery(param3).fadeOut();

		},function() {
			jQuery(param3).fadeIn();
			jQuery(param2).removeClass('closed');
		});
	}

	acardionDivs(".generalTitle",'.popupBuilder_general_postbox','.generalContent');
	acardionDivs(".effectTitle",'.popupBuilder_effect_postbox','.effectsContent');
	acardionDivs(".optionsTitle",'.popupBuilder_options_postbox','.optionsContent');
	acardionDivs(".dimentionsTitle",'.popupBuilder_dimention_postbox','.dimensionsContent');
	acardionDivs(".js-advanced-title",'.js-advanced-postbox','.advanced-options-content');
	acardionDivs(".js-special-title",'.popup-builder-special-postbox','.special-options-content');
}

beckend.prototype.fixedPostionSelection = function() {
	jQuery(".js-fixed-position-style").bind("click",function() {
		var sgelement = jQuery(this);
		var sgpos = sgelement.attr('data-sgvalue');
		jQuery(".js-fixed-position-style").css("backgroundColor","#FFFFFF");
		jQuery(this).css("backgroundColor","rgba(70,173,208,0.5)");
		jQuery(".js-fixed-postion").val(sgpos);
	});

	jQuery(".js-fixed-position-style").bind("mouseover",function() {
		jQuery(".js-fixed-position-style").css("backgroundColor","#FFFFFF");
		jQuery(this).css("backgroundColor","rgb(70,173,208)");
		jQuery(".js-fixed-position-style").each(function() {
			if (jQuery(this).attr("data-sgvalue") == jQuery('.js-fixed-postion').val())
				jQuery(this).css("backgroundColor","rgba(70,173,208,0.5)");
		});
	});

	jQuery(".js-fixed-position-style").bind("mouseout",function() {
		if(jQuery(".js-fixed-position-style").attr("data-sgvalue") !== jQuery(".js-fixed-postion").val() || jQuery(".js-fixed-postion").val() == 1) {
			jQuery(this).css("backgroundColor","#FFFFFF");
		}
		jQuery(".js-fixed-position-style").each(function() {
			if (jQuery(this).attr("data-sgvalue") == jQuery('.js-fixed-postion').val()) {
				jQuery(this).css("backgroundColor","rgba(70,173,208,0.5)");
			}
		});
	});

	if(jQuery('.js-fixed-postion').val()!='') {
		jQuery(".js-fixed-position-style").each(function(){
			if (jQuery(this).attr("data-sgvalue") == jQuery('.js-fixed-postion').val()) {
				jQuery(this).css("backgroundColor","rgba(70,173,208,0.5)");
			}
		});
	}
}

beckend.prototype.showInfo = function() {
		jQuery(".dashicons.dashicons-info").hover(
			function() {
				jQuery(this).next('span').css({"display": 'inline-block'});
			}, function() {
				jQuery(this).next('span').css({"display": 'none'});
			}
		);
}

beckend.prototype.opasictyRange = function() {
	if (typeof Powerange != "undefined") {
		var dec = document.querySelector('.js-decimal');
		function displayDecimalValue() {
			var dec = document.querySelector('.js-decimal');
			document.getElementById('js-display-decimal').innerHTML = jQuery(".js-decimal").attr("value");
		}
		var initDec = new Powerange(dec, { decimal: true, callback: displayDecimalValue, max: 1, start: jQuery(".js-decimal").attr("value") });
	}
}

beckend.prototype.showOptionsInfo = function(cehckboxSelector, param2) {
	if(jQuery(""+cehckboxSelector+":checked").length == 0) {
		jQuery("."+param2+"").css({'display': 'none'});
	}
	else
	{
		jQuery("."+param2+"").css({'display':'inline-block'});
	}

	jQuery(""+cehckboxSelector+"").bind("click",function() {
		if(jQuery(""+cehckboxSelector+":checked").length == 0) {
			jQuery("."+param2+"").css({'display':'none'});
		}
		else {
			jQuery("."+param2+"").css({'display':'inline-block'});
		}
	});
	jQuery('input.popup_theme_name').bind('mouseout',function() {
		jQuery('.theme1').css('display', 'none');
		jQuery('.theme2').css('display', 'none');
		jQuery('.theme3').css('display', 'none');
		jQuery('.theme4').css('display', 'none');
		jQuery('.theme5').css('display', 'none');
	});

}

beckend.prototype.subOptionContents = function() {
	this.showOptionsInfo("#js-auto-close", "js-auto-close-content");
	this.showOptionsInfo("#js-scrolling-event-inp", "js-scrolling-content");
	this.showOptionsInfo("#js-countris", "js-countri-content");
	this.showOptionsInfo("#js-popup-only-once", "js-popup-only-once-content");
	this.showOptionsInfo(".js-on-all-pages", "js-all-pages-content");
	this.showOptionsInfo(".js-on-all-posts", "js-all-posts-content");

	var that = this;
	var element = jQuery(".js-checkbox-acordion");
	element.each(function() {
		that.checkboxAcordion(jQuery(this));
	});

	element.click(function() {
		var elements = jQuery(this);
		that.checkboxAcordion(jQuery(this))
	});
}

beckend.prototype.addCountris = function() {
	var countyNames = [];
	var countryIsos = [];
	function addCountry(name,iso) {
		countyNames.push(name);
		countryIsos.push(iso);
		jQuery("#countryIso").val(countryIsos.join(','));
		jQuery('#countryName').tagsinput('add', countyNames.join(','));
	}
	jQuery(".addCountry").bind('click',function(){
		optionCountryName = jQuery(".optionsCountry option:selected").text();
		optionCountryIso = jQuery(".optionsCountry option:selected").val();
		addCountry(optionCountryName,optionCountryIso);
	});
	jQuery('input').on('itemRemoved', function(event) {
		var removeCountryName = event.item;
		countryNameIso = countyNames.indexOf(removeCountryName);
		countryIsos.splice(countryNameIso,1);
		countyNames.splice(countryNameIso,1);
		jQuery("#countryIso").val(countryIsos.join(','));
	});

	if(typeof popupCountries != "undefined" && typeof popupCountries != "undefined"){
		sgCountryNameArray = popupCountries.sgCountryName.split(",");
		sgCountryIsoArray = popupCountries.sgCountryIso.split(",");
		for(i=0; i <= sgCountryIsoArray.length; i++) {
			addCountry(sgCountryNameArray[i],sgCountryIsoArray[i]);
		}
	};
}

beckend.prototype.checkedOpenDiv = function() {
	
	var that = this;
	this.sgAllowCHangeButtonText();
	jQuery("[name='theme']").bind("change", function() {
		that.sgAllowCHangeButtonText()
	});
}
beckend.prototype.sgAllowCHangeButtonText = function() {

	if(jQuery("[sgpoupnumber='4'][name='theme']").prop( "checked" )) {
		jQuery(".theme-colse-text").removeClass("sg-hide");
	}
	else {
		jQuery(".theme-colse-text").addClass("sg-hide");
	}
}
