$(document).ready(function() {

	$("[data-width]:not(.text)").each(function() {

		if ($(this).attr("data-width") != "") {
			$(this).css({
				"flex" : "0 0 " + $(this).attr("data-width")
			});
		}
//		$(this).css("width" , "100%");
	});

	$("[data-inputmask]").each(function() {
		$(this).inputmask($(this).attr("data-inputmask"));
	});
/*
	$(".form_ref_el").each(function(){
		var el = $(this).find("[data-width]");

		var width = el.attr("data-width");
		$(this).width(width);

		el.css("width" , "100%");
		el.removeAttr("data-width");
		$(this).css("padding-left" , 5);
		$(this).css("padding-right" , 5);
	});

*/
	$("input[type=file]").change(function() {    
		var fileNameIndex = $(this).val().lastIndexOf("/") + 1;
		var file = $(this).val().substr(fileNameIndex);

		$(this).siblings(".fileupload").html(file);
	});


	$(".form-capcha-img").click(function(e){
        var obj = $(this);
        obj.find("img").attr("src", obj.attr("href") + "?code=" + obj.attr("data-code") + "&t=" + $.now());
		return false;
	});


	$(document).on(
		"submit" , 
		"form.ajax",
		function(e){
			var frm=$(this),
				formData = frm.serialize(),
				formStatus = frm.find(".formSubmit"),
				box = frm.find(".responsebox");

			if (box.hasClass("msg")) {
				box.addClass("remove");

				frm.find(".form-line.error").addClass("remove delayed");

				setTimeout(function() {
					box.removeClass("msg remove");
					frm.find(".form-line.error").removeClass("error remove delayed");

					frm.trigger("submit");
				}, 1000);
			}

		
			if (formStatus.length)
				formStatus.html("Sending Data...");


			if (!box.hasClass("msg")) 
				$.ajax({
					url:$(this).attr("action"),
					type:'post',
					data:formData,
					success: function(msg){

						var speed = 500;
						
						if (msg.indexOf("captcha:") != -1){
							$(".captcha-line").slideDown(500 , function(){
								$(".captcha-line").removeClass("captcha-hidden");
							});
							frm.find(".form-capcha-img").trigger("click");
							box.html(msg.replace("captcha:" , ""));
							//box.slideDown(speed);	

							frm.find("input[name=image_code]").val("");
						} else {
							box.html(msg);
							//box.slideDown(speed);	
						}					

						if (frm.hasClass("login")){

							var ok = frm.find(".success"),
								err = frm.find(".warning"),
								neu = frm.find(".neutral");

							if (ok.length && err.length && neu.length)	{

								if (box.find(".nError").length) {
									neu.fadeOut(speed);
									err.fadeIn(speed);
								} else {
									neu.fadeOut(speed);
									err.fadeOut(speed);
									ok.fadeIn(speed);
								}

							}

							if (msg.indexOf("captcha:") != -1){
								frm.find(".captcha-line").addClass("error");
							} else {
								if (msg.indexOf("nError") != "-1") {
									frm.find(".form-line:not(.captcha-line)").addClass("error");
								} else if (msg.indexOf("nSuccess") != "-1")	{
									frm.find(".form-line").addClass("success");									
								} 
							}

						}

						box.addClass("msg");
								
					}
				});

				if (formStatus.length)
					formStatus.html("");

			return false;

		}
	);		


	//forms

	var setValue = function () {
		var obj = $(this);
		obj.val(obj.attr("data-selected"));
	};

	$("select[data-selected]").each(setValue);

	if ($.fn.chosen) {
		$(".select:not(.notchosen)").each(function(e){
			$(this).chosen({
				width:						"100%",
				disable_search_threshold:	13,
				allow_single_deselect:		true
			}); 
		});
	}

	$(".doubleselect").each(function(e) {

		if ($(this).hasClass("sortable")){
			$(this).multiselect( { sortable : true , availableListPosition : "left" , splitRatio: 0.5 , sortMethod: null});
		} else {
			$(this).multiselect({ sortable: false , availableListPosition : "left" , splitRatio: 0.5});
		}
	});


});


$( window ).resize(function() {
  $(".doubleselect").multiselect("refresh");
});



function formCheckboxShowHide(elem , shown , hidden) {
	elem.change(formCheckboxShowHideHandler(shown, hidden));
	//run for the first time
	elem.trigger("change");
}

function formCheckboxShowHideHandler(shown, hidden){
	return function() {

		if ($(this).prop('checked')) {
			var fields = shown;
		} else {
			var fields = hidden;
		}


		for (i in fields){
			//check if fields exists
			if ($("#" + "XML_BODY_FIELD_" + i).length) {
				if (fields[i] == 1) {
					$("#" + "XML_BODY_FIELD_" + i).slideDown();
				} else {
					$("#" + "XML_BODY_FIELD_" + i).slideUp();
				}
			} else if ($("#" + i).length) {
				if (fields[i] == 1) {
					$("#" + i).slideDown();
				} else {
					$("#" + i).slideUp();
				}
			}
			
		}
	}
}

function showField(field) {
	$("#" + "XML_BODY_FIELD_" + field).slideDown();
}

function hideField(field) {
	$("#" + "XML_BODY_FIELD_" + field).slideUp();
}

function formPageUrl(elem, url) {

	elem.blur(formPageUrlHandler(elem, url));
	//run for the first time
	elem.trigger("blur");

}


function formPageUrlHandler(parent, url){
	return function() {
		
		if (!url.length){
			return false;
		}

		if (!url.val().length ){
			url.val(Name2Url(parent.val().trim()).toLowerCase() );
		}
	}
}



function formFieldAutoFill() {

	var parent = arguments[0];
	//arguments.shift();

	parent.blur(formFieldAutoFillHandler(parent, arguments));
	//run for the first time
	parent.trigger("blur");


}

function formFieldAutoFillHandler(parent , elements) {
	return function () {
		for (i in elements){

			if (elements[i].length){
				if ( !elements[i].val().length){
					elements[i].val(parent.val());

					if (elements[i].attr("name") == "seo_title"){
						$("#seo_title").trigger("change");
					}
				}
			}
		}		
	}
}



function formSelectShowHide(elem , elements ) {
	elem.change(formSelectShowHideHandler(elements));
	//run for the first time
	elem.trigger("change");
}

function formSelectShowHideHandler(elements){
	return function() {
		

		if ($(this).is(':radio')){
			if ($(this).filter(':checked').val()){
				var type = $(this).filter(':checked').val();
			} else {
				return false;

			}

		} else {

			if ($(this).is(':checkbox')) {

				if ($(this).is(':checked')){
					var type = 1;
				} else {
					var type = 0;

				}


			}else {
				if ($(this).val() == ""){
					var type = 0;
				} else {
					var type = $(this).val();
				}
			}
		}


		if (!elements[type]){

			if (typeof elements["default"] != "undefined"){
				type = "default";
			} else {
				return false;
			}
		}

		var fields = elements[type];



		for (i in fields){
			//check if fields exists


			if (i.indexOf("#") != -1){
				if (fields[i] == 1) {
					$(i).slideDown();
				} else {
					$(i).slideUp();
				}
			} else {
				if ($("#" + "XML_BODY_FIELD_" + i).length) {
					if (fields[i] == 1) {
						$("#" + "XML_BODY_FIELD_" + i).slideDown();
					} else {
						$("#" + "XML_BODY_FIELD_" + i).slideUp();
					}
				}
			}
		}

	}
}


function formSelectShowHideLink(trigger , fields) {

	formSelectShowHide(
		trigger , 
		{
			'default' : {
				[fields.global]			: 0,
				[fields.size]			: 0,
				[fields.module]			: 0,
				[fields.text]			: 0,
				[fields.link]			: 0,
				[fields.target]			: 0

			},
			1 : {
				[fields.global]			: 0,
				[fields.size]			: 1,
				[fields.module]			: 0,
				[fields.text]			: 1,
				[fields.link]			: 1,
				[fields.target]			: 1
			},
			2 : {
				[fields.global]			: 0,
				[fields.size]			: 1,
				[fields.module]			: 1,
				[fields.text]			: 1,
				[fields.link]			: 0,
				[fields.target]			: 1
			},
			3 : {
				[fields.global]			: 1,
				[fields.size]			: 1,
				[fields.module]			: 0,
				[fields.text]			: 1,
				[fields.link]			: 0,
				[fields.target]			: 1
			}
		}
	);

}

function UpdateCKE(){
	for ( instance in CKEDITOR.instances )
		CKEDITOR.instances[instance].updateElement();
}


if (typeof CKEDITOR != "undefined"){
	CKEDITOR.on('dialogDefinition', function(ev) {
		var dialogName = ev.data.name,
			dialogDefinition = ev.data.definition;
		if (dialogName === 'image') {
			dialogDefinition.removeContents('Upload');
		}
	});
}

function CSSClasses() {
	BrowsePopup('CSS Classes', 'index.php?mod=tools&sub=browsecss' , 884 , 550);
}


function formUpdateSelectOptionsJson( el , url , def) {

	def = typeof def !== 'undefined' ? def : "";
		
	$.getJSON(url, function(data) {
		el.html("");

		el.append('<option value="">[ select ]</option>');

		$.each(data, function(){
			el.append('<option value="'+ this.value +'">'+ this.name +'</option>');
		});

		el.val(def).trigger("change").trigger("chosen:updated");						
	});
}



function CM(id, profile , height) {

	if ($("#" + id).length) {

		var emmet_profile = "";

		profile			= profile		|| "html";
		height			= height		|| 500;


		switch (profile) {
			case "none":
				profile = "text/plain";
				emmet_profile = "";
			break;

			case "html":
				profile = "text/html";
				emmet_profile = "xhtml";
			break;

			case "css":
				profile = "text/css";
				emmet_profile = "css";
			break;	
		}

		CodeMirror.commands.autocomplete = function(cm) {

			switch (profile){ 
				case "javascript":
					CodeMirror.showHint(cm, CodeMirror.hint.javascript);
				break;

				case "css":
					CodeMirror.showHint(cm, CodeMirror.hint.css);
				break;

				default:
					CodeMirror.showHint(cm, CodeMirror.hint.html);
				break;		
			}		
		}

		var editor = CodeMirror.fromTextArea(document.getElementById(id), {
			mode		: profile,
			htmlMode	: true,
			profile		: emmet_profile,
			lineNumbers : true,
			height		: height,
			extraKeys	: {
				"Ctrl-Space"	: "autocomplete",
				'Tab'			: 'emmetExpandAbbreviation',
				'Enter'			: 'emmetInsertLineBreak'
			},					
		});

		if (emmet_profile != "") {
			emmetCodeMirror(editor);
		}

		return editor;
	}
}

