var MKGlobal = {
	formId: getURLParam('id'),
	formType: getURLParam('TYPE'),
	fb: getURLParam('advert_code'),
	mailRegEx: /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))$/i,
	urlRegEx: /^(file|gopher|news|nntp|telnet|http|ftp|https|ftps|sftp):\/\//,
	animating: false,
	unsaveinfo: 0,
	formSchemeId: null,
	formScheme: {
		// 颜色的信息
	},
	firstSave:true
};

MKGlobal.addUnsaveCount = function(){

	MKGlobal.unsaveinfo++;

	if(MKGlobal.unsaveinfo > 0 && $('.btn_example_save').hasClass('allsaved') ){
		$('.btn_example_save').removeClass('allsaved').text('保存表单');
	}
	if(MKGlobal.unsaveinfo === 0 && !$('.btn_example_save').hasClass('allsaved') ){
		$('.btn_example_save').addClass('allsaved').text('已保存');
	}
};
var formBuilderUnSaveMsg = "您有编辑的内容尚未保存，确定不保存离开吗？";
var unSavedHandle = function () {
    if (MKGlobal.unsaveinfo !== 0) {
        if(confirm(formBuilderUnSaveMsg)){
            $(window).unbind('beforeunload');
            return true;
        }else{
            return false;
        }
    }
    return true;
};

$(document).ready(function ($) {
	//头部active属性
	$("#header .list_left li").not(".formManager").removeClass("active");
	$("#header .list_left .formManager").addClass("active");

	$(".formBuilder_example").niceScroll({
		cursorborder: "",
		cursorcolor: "#999",
		scrollspeed: 64,
		horizrailenabled: false
	});

	$(".formBuilder_edit").niceScroll({
		cursorborder: "",
		cursorcolor: "#999",
		zindex: "10"
	});
	$(".formBuilder_color .style_pad").niceScroll({
		cursorborder: "",
		cursorcolor: "#999"
	});
	$(".formBuilder_color .style_design_item").niceScroll({
		cursorborder: "",
		cursorcolor: "#999"
	});
	// $(".style_design").getNiceScroll().hide();

	$(".group_operate").niceScroll({
		cursorborder: "",
		cursorcolor: "#999"
	});

	$('.logic_scrollable').niceScroll({
		cursorborder: "",
		cursorcolor: "#999"
	}).hide();

	$('.formBuilder_feedback_email_dropDown').niceScroll({
		cursorborder: "",
		cursorcolor: "#999"
	});

	renderPage();

	// ---onclick

	$(".formBuilderUnSaveEventOn").on('click', unSavedHandle);
    $(window).bind('beforeunload', function () {
        if (MKGlobal.unsaveinfo !== 0) {
            return formBuilderUnSaveMsg;
        }
    });
});


// -- basic

function getURLParam(val) {
	var reg = new RegExp("[?&]" + val + "=([^?&]*)[&]?", "i");
	var match = location.search.match(reg);
	return match == null ? false : match[1];
}

// render page 
// 初始化页面中的各种组件的事件
function renderPage() {
	// -- 编辑切换
	var $color = $('.formBuilder_color');
	$(".formBuilder_interim_edit").click(function () {
		var $this = $(this),
			index = $(".formBuilder_interim_edit").index($this),
			isColor = $this.hasClass('formBuilder_interim_edit_color');

		$this.addClass('formBuilder_interim_edit_active').siblings('.formBuilder_interim_edit').removeClass('formBuilder_interim_edit_active');

		if(isColor){	// 为了适应多种屏幕下的显示效果做的更改
			$color.removeClass('color_hide');
		}
		$(".formBuilder_edit:eq(" + index + ")").show().siblings('.formBuilder_edit').addClass('formBuilder_edit_hidden').hide();
		if($('.formBuilder_interim_edit_color:visible').length>0 && !isColor){
			$color.addClass('color_hide');
		} else {
			$color.removeClass('color_hide');
		}
	});

	var color = 'Blue';

	if(MKGlobal.formType == 2){
		color = 'Orange';
	}

	$(".form_edit_expand_title").click(function(){
		var $container = $(this).siblings('.form_edit_expand_container'),
			$this = $(this);
		if($container.hasClass('form_expand_show')){
			$container.slideUp(300,function(){
				$container.removeClass('form_expand_show');
				$('.formBuilder_edit').getNiceScroll().resize();
				$this.find('i').attr('class','i i-arrow-down4 pull-right');
			});
		} else {
			$container.addClass('form_expand_show').slideDown(300,function(){
				$('.formBuilder_edit').getNiceScroll().resize();
				$this.find('i').attr('class','i i-arrow-up4 pull-right');
			});
		}

	}).append('<i class="i i-arrow-up4 pull-right"></i>');

	// 载入 表单  -- 队列1
	getFormBy(MKGlobal.formId);
	$(".formBuilder_example").getNiceScroll().resize();

	// 载入 配色信息 -- 队列2
	getFormScheme();

	// 载入群组信息、渲染标签信息
	renderFlag();
	renderGroup();
	renderButton();
	init();

	$(document).dequeue('MKFORMEDIT');
}

//读取form
function getFormBy(id) {
	$(document).queue('MKFORMEDIT', function () {
		$.ajax({
			url: 'handleGetForm',
			type: 'POST',
			data: {id:id},
			dataType: 'JSON'
		}).done(function (data) {
			//console.log(data);
				var formJSON,
					tmpJSONStr,
					tmpContactFlag = [
						[],
						[]
					];
				if (data.flag) {
					// MKGlobal.formSchemeInfo = parseFormSchemedata.data.style;
					// //--- storeage as pre
					MKGlobal.preFormSchemeInfo = data.data.style;

					tmpJSONStr = data.data.template||'{"form":{"title":"空白表单","logo":"","subtitle":"从头开始创建您的表单"},"component":[]}';
					tmpJSONStr = tmpJSONStr.replace(/"FLAGS":'\[(.*)\]'/g,function($,$1){
						return '"FLAGS":'+JSON.stringify('['+$1+']');
					}).replace(/undefined/g,'false');
					// console.log(tmpJSONStr);
					tmpJSONStr = tmpJSONStr.replace(/\t/g,'\\t');

					tmpJSONStr = tmpJSONStr.replace(/[\n\r]/igm,function($,$1){
						return '\\n';
					});
                    if(MKGlobal.formType == 1 && data.data.type && data.data.type == 2){
                        window.location.href = "formBuilderLogic.php?ID="+data.data.id +"&TYPE=2"+"&FB="+MKGlobal.fb;
                    }
					try {
						formJSON = JSON.parse(tmpJSONStr);
					} catch (e) {
						$('.globalLoading').find('.info').text('啊欧,打开表单遇到问题…请联系我们一起解决(' + e.name + ')').width(400);
					}

					MKGlobal.formScheme.wallpaper += ';background-image:'+(decodeURIComponent(formJSON.form.backgroundimg)||'')+';background-repeat:'+(formJSON.form.backgroundtype||'');

					MKGlobal.formSchemeStruct = parseFormScheme(data.data.style);

					MKGlobal.preFormJSON = $.toJSON(tmpJSONStr);

					// 保存些一定会用到的数值

					MKGlobal.formInfo = {
						newContact: formJSON.form.contact,
						contactFlag: (formJSON.form.FLAGS) ? JSON.parse(formJSON.form.FLAGS):'',
						contactGroup: (formJSON.form.GROUPS) ? formJSON.form.GROUPS.split(";") : [],
						sendMailInfo: {
							email: formJSON.form.sendToEmail||'',
							name: formJSON.form.sendToName||'',
							needSend: (((formJSON.form.sendToEmail||'').length>0)?formJSON.form.sendMail:false),
							state: data.data.sendToEmailStatus
						},
                        webHookUrl: formJSON.form.webhookurl|| [],
                        prevPage: formJSON.form.prev_page||0,
						afterSubmitForm: {
							type: '',
							value: ''
						},
						formControl: {
							startDate: data.data.startDatetime || '',
							stopDate: data.data.stopDatetime || "",
							maxFeedback: data.data.max || ''
						},
						feedbackNum: data.data.fbNum,
						formName: data.data.name,
						formShare: (formJSON.form.formShare !== false),
						formRes: (data.data.publicChart===1?true:false),
						formResDetail: (data.data.openFeedback===1?true:false),
                        feedbackDetailPassword: (data.data.openFeedbackPwd),
						formRandomCode: (data.data.feedbackcode===1?true:false),
						formMN: (parseInt(formJSON.form.mn,10) || false),
						formSubmitOnce: data.data.submitOnce,
						onlyWechat: data.data.onlyWechat,
						formPaymentInfo: (formJSON.form.paymenttype||"").split(';'),
						background: decodeURIComponent(formJSON.form.backgroundimg||''),
						backgroundtype: (formJSON.form.backgroundtype||''),
						formLogo: decodeURIComponent(formJSON.form.logo||''),
						logoAvailable: false,
						formTitleBackground: decodeURIComponent(formJSON.form.titlebackground||''),
						titlebkAvailable: false
					};

					if (MKGlobal.formInfo.contactFlag) {
						$.each(MKGlobal.formInfo.contactFlag, function (n, v) {
							tmpContactFlag[0].push(v.N);
						});
						MKGlobal.formInfo.contactFlag = tmpContactFlag;
					}
					$(".formBuilder_example_form").formCreator({
						jsonObject: formJSON
					});

					// ---- CSS write !!!
					MKFORM.formUtility.formSchemeCSSGenerator();

					// 代收状态判断
					switch ( data.data.payAgencyStatus ) {
						case 0:
							$("#pay_application-apply").show().find('.btn-primary').click(function(event) {
								TINY.box.show({
									html:$(".popwin_applyPay_template").html(),
									width: 450,
									height: 250,
									animate:true,
									boxid: 'popwin_applyPay',
									close:true,
									openjs: function(){
										var pop_win = $("#popwin_applyPay");
                                        pop_win.find(".btn_confrim").removeClass('btn_gray').addClass('btn_blue').click(function(event) {
                                            $button = $(this);
                                            $.ajax({
                                                url: 'handler/handleApplyFormPay.php',
                                                type: 'POST',
                                                dataType: 'JSON',
                                                data: {
                                                    "DATA": '{"PHONE":""}'
                                                },
                                                success: function (data) {
                                                    $button.parent().html('<a href="http://wiki.mikecrm.com/pay-agreement" class="button btn_blue" style="margin-top: 50px;" target="_blank">查看代收协议，填写申请表</a>');
                                                    $("#pay_application-doing").show();
                                                    $("#pay_application-apply").hide();
                                                }
                                            });
                                        });
									}
								});
							});
							break;
						case 1:
							$("#pay_application-doing").show();
							break;
						case 2:
							$("#pay_application-pass").show();
							break;
					}

					// -- disable all;

					$('.form_component').find('input').attr('disabled', true);
					$('.form_component').find('textarea').attr('disabled', true);
					$('.form_component').find('select').attr('disabled', true);
					$(document).dequeue('MKFORMEDIT');
				} else {
					$('.globalLoading').find('.info').text('抱歉，打不开这张表单…');
				}

			});

	});
}



// 将字符串的 样式转换成 obj
function parseFormScheme(str){
	var o = {},
		cssArray,
		styleList = ['fw','fs','flh','wb','wt','img','imgp','imgr','imgf','lb','lt','logo','timg','fb','ft','it','hb','ht'],
		defaultsValue = ['750px', '16px', '25px', 'F4F5F0', '333333', '', 'left', '', '', 'FEFEFE', '222222', '', '', 'FFFFFF', '333333','333333', 'FFF8DC', '333333'];
	if(str){
		str += '';
		cssArray = str.split(',');
		for(var i=0,len = styleList.length; i<len; i++){
			o[styleList[i]] = cssArray[i]||defaultsValue[i];
		}
	}
	return o;
}

// 读取配色方案
function getFormScheme() {
	function t(o,flag){
		var r = '';
		r += '<div class="formBuilder_color_items" schemeInfo="' + o.info.toUpperCase() + '" >';
		if(!flag){
			r += '<div class="removeself_color" schemeid="'+o.id+'"></div>';
		}
		r += '<div class="color_show_block csbs" style-name="formBuilder_color_wallpaper" bk="'+o.wb+'" t="'+o.wt+'" style="background-color:#'+o.wb+';color:#' + o.wt + '">';
		r += '<div class="csb_title csbs" style-name="formBuilder_color_title" bk="'+o.lb+'" t="'+o.lt+'" style="background-color:#'+o.lb+';color:#'+o.lt+';">'+o.name+'</div>';
		r += '<div class="csb_contect csbs" style-name="formBuilder_color_form" bk="'+o.fb+'" t="'+o.ft+'" style="background-color:#'+o.fb+';color:#'+o.ft+';">';
		r += '<p class="csb_stitle" style="background-color:#'+o.ft+';color:#'+o.ft+';"></p>';
		r += '<p class="csb_des csbs" style-name="formBuilder_color_instruction" t="'+o.it+'" style="background-color:#'+o.it+';color:#'+o.it+';"></p>';
		r += '<p class="csb_highlight csbs" bk="'+o.hb+'" t="'+o.ht+'" style-name="formBuilder_color_highlight" style="background:#' + o.hb + ';color:#' + o.ht + '">';
		r += '</div></div></div>';
		return r;
	}
	$(document).queue('MKFORMEDIT', function () {
	var data = {"flag":false}
				var colorItemHTML = '';
				if (data.flag) {
					$(".formBuilder_color").find('.style_pad').empty();
					colorItemHTML = '';
					$.each(data.data, function (name, value) {
						var o = parseFormScheme(value.css);
						o.id = value.id;
						o.name = value.name;
						o.info  = value.css;
						colorItemHTML += t(o);
					});
					$.each(default_scheme, function (name, value) {
						var o = parseFormScheme(value.css);
						o.name = value.name;
						o.info  = value.css;
						colorItemHTML += t(o,true);
					});

					$(colorItemHTML+'<div class="clearB"></div>').appendTo(".style_pad");
					$(".formBuilder_color .style_pad").getNiceScroll().resize();
					// console.log(MKGlobal.preFormSchemeInfo);
					if (MKGlobal.preFormSchemeInfo) {
						$(".formBuilder_color_items[schemeinfo='" + MKGlobal.preFormSchemeInfo.toUpperCase() + "']").addClass("active_color");
						$(".formBuilder_color_items[schemeinfo='" + MKGlobal.preFormSchemeInfo.toUpperCase().replace('LEFT','') + "']").addClass("active_color");
					} else {
						$(".formBuilder_color_items[schemeinfo='640PX,16PX,25PX,F4F5F0,000000,,,,,FFFFFF,000000,,,FFFFFF,000000,7C7C7C,FFF8DC,000000']").addClass("active_color");
					}
					$(".formBuilder_color").getNiceScroll().resize();
				} else {
					$(".formBuilder_color").find('.style_pad').empty();
					colorItemHTML = '';
					$.each(default_scheme, function (name, value) {
						var o = parseFormScheme(value.css);
						o.name = value.name;
						o.info  = value.css;
						colorItemHTML += t(o,true);
					});

					$(colorItemHTML+'<div class="clearB"></div>').appendTo(".style_pad");
					$(".formBuilder_color .style_pad").getNiceScroll().resize();
					// console.log(MKGlobal.preFormSchemeInfo);
					if (MKGlobal.preFormSchemeInfo) {
						$(".formBuilder_color_items[schemeinfo='" + MKGlobal.preFormSchemeInfo.toUpperCase() + "']").addClass("active_color");
						// console.log(MKGlobal.preFormSchemeInfo.toUpperCase().replace('LEFT',''));
						$(".formBuilder_color_items[schemeinfo='" + MKGlobal.preFormSchemeInfo.toUpperCase().replace('LEFT','') + "']").addClass("active_color");
					} else {

						$(".formBuilder_color_items[schemeinfo='640PX,16PX,25PX,F4F5F0,000000,,,,,FFFFFF,000000,,,FFFFFF,000000,7C7C7C,FFF8DC,000000']").addClass("active_color");
					}
				}
				$(document).dequeue('MKFORMEDIT');

		// $(document).dequeue('MKFORMEDIT');
	});
}

// 获取所有的群组
function getGroup(callback) {
	var data = {"flag":false}
			if (data.flag) {
				$(".group_operate li:not(:first)").remove();
				var groupname, groupid;
				for (var i in data.data) {
					groupname = data.data[i].name;
					groupid = data.data[i].id;
					// ---
					if (!MKGlobal.formInfo.contactGroup[groupid]) {
						$(".group_operate li:first").after("<li><span class='group_checkbox'><input type='checkbox' groupsId='" + groupid + "' /></span>" + groupname + "</li>");
					} else {
						$(".group_operate li:first").after("<li><span class='group_checkbox checked'><input type='checkbox' checked='checked' groupsId='" + groupid + "' /></span>" + groupname + "</li>");
					}
				}
				if (Object.prototype.toString.call(callback) == '[object Function]') {
					callback();
				}

				$(".dropdown_group").getNiceScroll().resize();
			}
}

function addGroup(groupname) {
	$.ajax({
		url: 'handleAddGroup.html',
		type: 'POST',
		dataType: 'JSON',
		data: {
			"DATA": '{"NAME":' + JSON.stringify(groupname) + '}'
		},
		success: function (data) {
			if (data.flag) {
				$(".saveToGroup").getNiceScroll().hide();
				$(".saveToGroup").animate({top:"10px",opacity:0},100,function(){
					$(this).css("display","none").find("li").hide();
				});
				MKGlobal.formInfo.contactGroup[data.data.id] = 1;
				getGroupLast(data.data.id);
			}
		}
	});
}

function getGroupLast(newgroupid) {
	$.ajax({
		url: 'handleGetAllGroup.php',
		type: 'POST',
		dataType: 'JSON',
		success: function (data) {
			if (data.flag) {
				for (var i in data.data) {
					var groupname = data.data[i].name;
					var groupid = data.data[i].id;
					if (groupid == newgroupid) {
						$(".group_operate li:first").after("<li><span class='group_checkbox checked'><input type='checkbox' checked='checked'  groupsId='" + groupid + "' /></span>" + groupname + "</li>");
						$(".dropdown_group").before("<p class='viewContact_group' groupid='" + groupid + "'>" + groupname + "</p>");
					}
				}
			}
		}
	});
}
$('.btn_example_save11').click(function(){
	var TEMPLATE = $.toJSON($(".formBuilder_example_form").formCreator("generate"));
	var js_customer_service = $('#js_customer_service').val();
	var cs_customer_types = $('#cs_customer_types').val();
	var btn_name = $('#btn_name').val();
	var jump_url = $('#jump_url').val();
	var style = __saveLineGenerate();
    generateJSON($(this), function (data) {
        MKGlobal.unsaveinfo = 0;
        MKGlobal.firstSave = false;
        $('.btn_example_save').addClass('allsaved').text('已保存');
        return true;
    });
	console.log(style)
})
function renderGroup() {
	// ----  没有！重构！！！
	// 1. 事件绑定
	// 2. 渲染内容
	$(document).queue('MKFORMEDIT', function () {
		// ---

		getGroup(function () {
			var tmpGroup = [];
			for (var i in MKGlobal.formInfo.contactGroup) {
				tmpGroup[i] = MKGlobal.formInfo.contactGroup[i];
			}
			MKGlobal.formInfo.contactGroup = {};
			$.each(tmpGroup, function (i) {
				$("[groupsid=" + parseInt(tmpGroup[i]) + "]").show().trigger("click").hide();
			});
			MKGlobal.unsaveinfo = 0;
			// $('.btn_example_save').addClass('allsaved').text('已保存');

			if (MKGlobal.formInfo.newContact === false && MKFORM.formUtility.formContactCheck($('.form_component').children('.ui-draggable'))) {
				$("#autoAddContact").removeAttr('checked').parent().removeClass('checked').siblings('.formCreateContacts').hide();
			}
			// ---

			if ($('.viewContact_group').not('.formGroupName').length > 0) {
				$('.formGroupName').remove();
			}

		});

		var formGroupName = MKGlobal.formInfo.formName;
		var date = new Date();
		var dateObject = MKFORM.formUtility.getSimpleDate(date);
		$(".formGroupName").text(formGroupName + "_" + dateObject);

		$(".add_creatGroup").die('click').live("click",function(e){
			e.stopPropagation();
			$(this).closest(".group_firstLi").find('.cerateGroup_field').remove();
			$(this).closest(".group_firstLi").append("<span class='cerateGroup_field'><input class='input input_creatGroup' maxlength='8' /><a class='btn btn-primary btn_creatGroup'>创建</a><a class='btn_cancleCreatGroup'>取消</a></span>").find(".input").focus();
			inputval();
		});
		$(".btn_cancleCreatGroup").die('click').live("click",function(e){
			e.stopPropagation();
			$(this).closest(".cerateGroup_field").remove();
		});
		$(".btn_creatGroup").die('click').live("click",function(e){
			e.stopPropagation();
			$(this).closest(".cerateGroup_field").remove();
			var groupname = $(this).siblings(".input_creatGroup").val();
			if (groupname != "") {
				addGroup(groupname);
			}
		});


		$(".group_operate").find("li:not(.group_firstLi)").die('click').live("click", function () {
			var groupid = $(this).find(".group_checkbox input").attr("groupsId");
			var groupname = $(this).text();
			if ($(this).find(".group_checkbox").hasClass("checked")) {
				$(this).find(".group_checkbox").removeClass("checked").find(':checkbox').attr("checked", false);
				$(this).closest(".dropdown_group").siblings(".viewContact_group").each(function () {
					if ($(this).attr("groupid") == groupid) {
						$(this).remove();
						MKGlobal.formInfo.contactGroup[groupid] = 0;
					}
				});
			} else {
				$(this).find(".group_checkbox").addClass("checked").find(':checkbox').attr("checked", "checked");
				$(this).closest(".dropdown_group").before("<p class='viewContact_group' groupid='" + groupid + "'>" + groupname + "</p>");
				MKGlobal.formInfo.contactGroup[groupid] = 1;
			}
			MKGlobal.addUnsaveCount();
		});

		$(document).dequeue('MKFORMEDIT');
	});
}

function renderFlag() {
	$(document).queue('MKFORMEDIT', function () {
		$(".formBuilder_edit_tag").mgTag({
			isRequirePic: false,
			isRequireFlow: false,
			isNeedFloat: false,
			defaultsValue: MKGlobal.formInfo.contactFlag,
			insertFinish: function(){
				MKGlobal.addUnsaveCount();
			},
			deleteFinish:function(){
				MKGlobal.addUnsaveCount();
			}
		});
		$(document).dequeue('MKFORMEDIT');
	});
}


function renderButton() {
	$(document).queue('MKFORMEDIT', function () {
		$(".btn_example_save").unbind('click').bind("click", function () {
			// ---保存表单
		//	_data = '{"FRID":"'+MKGlobal.formId+'","FIELDVALUES":{"TEMPLATE":'+$.toJSON($(".formBuilder_example_form").formCreator("generate"))+',"STYLE":'+JSON.stringify(MKGlobal.formStyle)+'}}';

			if(!$(this).hasClass('allsaved') || MKGlobal.firstSave){
				//if ($('.formGroupName').length > 0 && $('#autoAddContact').attr('checked')=='checked') {alert(321)
					$.ajax({
						url: 'handleAddGroup.html',
						type: 'POST',
						dataType: 'JSON',
						data: {
							"DATA": '{"NAME":' + JSON.stringify($('.formGroupName').text()) + '}'
						},
						success: function (data) {

							if (data.flag) {
						//		$(".formGroupName").attr("groupid", data.data.id);
								$(".formGroupName").removeClass("formGroupName");
								generateJSON($(this), function (data) {
									MKGlobal.unsaveinfo = 0;
									MKGlobal.firstSave = false;
									$('.btn_example_save').addClass('allsaved').text('已保存');
									return true;
								});
							}
						}
					});
				//} else {
				//	generateJSON($(this), function (data) {
				//		MKGlobal.unsaveinfo = 0;
				//		MKGlobal.firstSave = false;
				//		$('.btn_example_save').addClass('allsaved').text('已保存');
				//		return true;
				//	});
				//}
			}
			// ---
			$('.design_view').trigger('click');
		});
		//生成表单
		$('.btn_example_generate').unbind('click').bind('click', function () {console.log(111)
			if ($('.formGroupName').length > 0 && $('#autoAddContact').attr('checked')=='checked') {
				$.ajax({
					url: '/advert/Advert/createForm',
					type: 'POST',
					dataType: 'JSON',
					data: {
						"DATA": '{"NAME":' + JSON.stringify($('.formGroupName').text()) + '}'
					},
					success: function (data) {
						if (data.flag) {
							$(".formGroupName").attr("groupid", data.data.id);
							$(".formGroupName").removeClass("formGroupName");
							generateJSON($(this), function (data) {
								MKGlobal.unsaveinfo = 0;
								if (MKGlobal.fb !== false) {
									location.href = 'formPreview/'+MKGlobal.formId+'.html';
								//	location.href = 'formRelease.php?ID=' + MKGlobal.formId + '&FB=' + MKGlobal.fb + '&BUILDER=1'+ '&TYPE=' + MKGlobal.formType;
								} else {
									location.href = 'formPreview/'+MKGlobal.formId+'.html';
								//	location.href = 'formRelease.php?ID=' + MKGlobal.formId + '&BUILDER=1'+ '&TYPE=' + MKGlobal.formType;
								}
							});
						}
					}
				});
			} else {
				generateJSON($(this), function (data) {
					MKGlobal.unsaveinfo = 0;
					if (MKGlobal.fb !== false) {
						location.href = 'formPreview/'+MKGlobal.formId+'.html';
					//	location.href = 'formRelease.php?ID=' + MKGlobal.formId + '&FB=' + MKGlobal.fb + '&BUILDER=1'+ '&TYPE=' + MKGlobal.formType;
					} else {
						location.href = 'formPreview/'+MKGlobal.formId+'.html';
					//	location.href = 'formRelease.php?ID=' + MKGlobal.formId + '&BUILDER=1'+ '&TYPE=' + MKGlobal.formType;
					}
				});
			}
			$('.design_view').trigger('click');
		});

		// wsq_gener_btn
		$('.btn_wsq_generate').unbind('click').bind('click',function (){
			if ($('.formGroupName').length > 0 && $('#autoAddContact').attr('checked')=='checked') {
				$.ajax({
					url: 'handleAddGroup.html',
					type: 'POST',
					dataType: 'JSON',
					data: {
						"DATA": '{"NAME":' + JSON.stringify($('.formGroupName').text()) + '}'
					},
					success: function (data) {
						if (data.flag) {
							$(".formGroupName").attr("groupid", data.data.id);
							$(".formGroupName").removeClass("formGroupName");
							generateJSON($(this), function (data) {
								MKGlobal.unsaveinfo = 0;
								// 生成的弹窗
							});
						}
					}
				});
			} else {
				generateJSON($(this), function (data) {
					MKGlobal.unsaveinfo = 0;
					// 生成的弹窗
					TINY.box.show({
						html:$(".popwin_publishForm").html(),
						width:414,
						height:224,
						fixed:false,
						boxid: 'pop_publish-form',
						maskid:'blackmask',
						maskopacity:40,
						openjs:function(){
							$box = $('#pop_publish-form');
							$.ajax({
								url: 'handler/handleSaveForm.php',
								type: 'POST',
								data: {
									"DATA": "{\"FRID\":\""+MKGlobal.formId+"\"}"
								},
								dataType: 'JSON'
							}).done(function (res){
								if(res.flag){
									$box.find('.popwin_formNameContent').empty().html('<p class="popwin_tips"></p><p><a class="button btn_blue js_send_dail">发布消息到微社区</a></p><p><a href="'+uriGener('')+'" class="button btn_blue">回到表单列表</a></p>').show();

									$box.on('click.sthread','.js_send_dail',function(){
										var $this = $(this),
											$list = $this.closest('.wei_form_item');
										if(!$this.hasClass('send')){
											$this.addClass('send');
											$.ajax({
												url: 'handler/handleWsqThreadNew.php',
												type: 'POST',
												dataType: 'json',
												mode: 'abort',
												data: {
													DATA: JSON.stringify({
														'CONTENT': '我创建了一个表单,快去填写吧~ http://m.wsq.qq.com/app?sId='+getURLParam('sId')+'&appId='+getURLParam('appId')+'&extra='+res.data+''
													})
												}
											}).done(function(){
												$box.find('.js_send_dail').text('发布成功!');
											});
										}

									});
								}
							});
						}
					});
				});
			}
			$('.design_view').trigger('click');
		});

		$('.btn_example_preview').unbind('click').bind('click', function () {

			var nw = window.open();
			var previewHref = '/code/'+MKGlobal.fb+'/0';
			nw.location = previewHref;
			nw.location = previewHref;

			$('.design_view').trigger('click');
		});

		$('.btn_example_toStep1').unbind('click').bind('click',function(){
			var _self = $(this);
			TINY.box.show({
				html:$(".popwin_toStep1").html(),
				width: 414,
				animate:true,
				boxid: 'goto_template',
				close:true,
				openjs: function(){
					var $box = $('#goto_template');
					$box.find(".btn_cancel").click(function(){
						TINY.box.hide();
					});

					if(MKGlobal.unsaveinfo !== 0){
						MKGlobal.unsaveinfo = 0;
						$box.find('.popwin_content p').text('还有内容未保存，是否放弃当前编辑内容？');
					}

					$box.find(".btn_confrim").click(function(){
						if (MKGlobal.fb !== false) {
							location.href = 'getCreateHtml.html?ID=' + MKGlobal.formId + '&FB=' + MKGlobal.fb ;
						} else {
							location.href = 'getCreateHtml.html?ID=' + MKGlobal.formId ;
						}
					});
				}
			});
		});

		$(document).dequeue('MKFORMEDIT');
	});
}

//保存form
// get Global 中的对象
function alterForm(formId, alertFieldValues, btn, callback) {
	//console.log(alertFieldValues)
	// var _value = (newValue)?newValue:"\" \"",
	// 	_formData = "{\"FRID\":\""+formId+"\",\"FIELD\":\""+alterType+"\",\"VALUE\":"+_value+"}";
	var _formData = '{"FRID":"' + formId + '","FIELDVALUES":{' + alertFieldValues + '}}';
	var js_customer_service = $('#js_customer_service').val();
	var cs_customer_types = $('#cs_customer_types').val();
	var btn_name = $('#btn_name').val();
	var jump_url = $('#jump_url').val();
	$('.btn_example_save1').attr("disabled","disabled");

	$.ajax({
		//url: 'handler/handleAlterForm.php',
		url: '/advert/Advert/createForm',
		type: 'POST',
		data: {
			"DATA": _formData,
			"js_customer_service" : js_customer_service,
			"cs_customer_types" : cs_customer_types,
			"btn_name" : btn_name,
			"jump_url" : jump_url
		},
		beforeSend: function () {
			$('.btn_example_save1').removeClass("btn-primary").addClass("btn_gray").text("保存中...");
		},
		dataType: 'JSON',
		success: function (data) {
            if(data.code == 200){
				alert('操作成功');
				//$('.btn_example_save1').removeAttr("disabled");
				//document.getElementById(".btn_example_save1").disabled=false;
				$('.btn_example_save1').removeClass("btn_gray").addClass("btn-primary").text("已保存");
            }else{
				$('.btn_example_save1').removeAttr("disabled");
                alert('操作失败');
            }
			/*if (btn) {
				if (btn.hasClass("btn_example_save1")) {
					btn.removeClass("btn_gray").addClass("btn-primary").text("保存表单");
				} else {
					btn.removeClass("btn_gray").addClass("btn-primary").find("span").text("生成表单");
				}
			}*/
		}
	});
}

function __saveLineGenerate(){
	var styleList = ['fw','fs','flh','wb','wt','img','imgp','imgr','imgf','lb','lt','logo','timg','fb','ft','it','hb','ht'],
		defaultsValue = ['750px', '16px', '25px', 'F4F5F0', '333333', '', 'left', '', '', 'FEFEFE', '222222', '', '', 'FFFFFF', '333333','333333', 'FFF8DC', '333333'],
		ans = [];
	for(var i=0,len = styleList.length; i<len; i++){
		ans[i] = MKGlobal.formSchemeStruct[styleList[i]]||defaultsValue[i];
	}

	return ans.join(',');
}

//function generateJSON($ui, callback) {
$('.btn_example_save1').click(function(){
	//存储json串
	var json,
		flags = [],
		groups = [],
		contactState = true,
		mailSenderState = true,
		sendToEmail = '',
        webHookUrl = [],
        prevPage = 0,
		sendToName = '',
		sendToEmailArray = null,
	// ---
		fieldValues = "",
		startTime = "",
		endTime = "",
		endFeedbackNum = "",
		endSubmitOnce = "",
	// ---
		setPreValueList = [];

	$(".mgTagItem").each(function () {
		var value = $(this).find("span").text();
		flags.push('{\\"N\\":\\"' + value + '\\",\\"L\\":\\"' + encodeValue(value) + '\\"}');
	});
	$(".viewContact_group").each(function () {
		groups.push($(this).attr("groupid"));
	});

	contactState = ($('#autoAddContact').attr('checked') == 'checked');
	mailSenderState = ($('#autoSendMail').attr('checked') == 'checked');

	if (mailSenderState) {
		// -- 模拟回车，以防止没有输入完全的邮箱不录入
		var $feedbackEmail = $('.feedback_email'),
			feedbackEmail = $feedbackEmail.attr('id'),
			$feedbackEmailInput = $('#'+feedbackEmail+'-tagInput'),
			__e = jQuery.Event("keypress");
		__e.which = 13;

		$feedbackEmailInput.val($feedbackEmailInput.val()+String.fromCharCode(__e.which));
		$feedbackEmailInput.trigger(__e);

		sendToEmail = $feedbackEmail.mikeTag_AllTag();
		sendToEmailArray = [];
		$.each(sendToEmail, function (email, emailId) {
			sendToEmailArray.push(email);
		});
		sendToEmail = sendToEmailArray.join(';');
		sendToName = $('.feedback_name').val();
		if(sendToEmailArray.length<1){
			mailSenderState = false;
		}
	}
	// }
    webHookUrl = MKGlobal.formInfo.webHookUrl;
    prevPage = MKGlobal.formInfo.prevPage;

	// 保存
	//if (MKGlobal.formId) {
		// 将标签信息写入表单中等待存储
		var typeMap = ['showtext', 'openlink'];
		// console.log($('#payment_ali').attr('checked')=='checked');
		$(".form_title").attr({
			"flags": "\"[" + flags.join(",") + "]\"",
			"groups": groups.join(";"),
			"contact": contactState,
			"sendmail": mailSenderState,
			"sendtoemail": sendToEmail,
			"sendtoname": sendToName,
            "webhookurl": JSON.stringify(webHookUrl),
            "prev_page": prevPage,
			"formShare": ($('#showShareButton').attr('checked')=='checked'||false),
			"onlyWechat": ($('#openFormOnlyByWeixin').attr('checked')=='checked'||false),
			"formRes": ($('#endFormSubmitSawRes').attr('checked')=='checked'||false),
			"formResDetail": ($('#endFormSubmitSawResDetail').attr('checked')=='checked'||false),
			"formRandomCode": ($('#endFormRandomCode').attr('checked')=='checked'||false),
			"mn": (MKFORM.serialCount._getCount()),
			"paymenttype": ($('#payment_ali').attr('checked')=='checked')?'ALIPAY':'',
			"backgroundimg": $('.formBuilder_example').css('background-image'),
			"backgroundtype": $('.formBuilder_example').css('background-repeat'),
			'titlebackgroundimg': ($('.form_title').attr('titlebackgroundimg')||''),
			"type": $.inArray($('.aftersubmit').find('.radio>input[checked="checked"]').val(), typeMap),
			"finishForm": $('.aftersubmit').find('.formBuilder_edit_input').val(),
            "feedbackDetailPassword": $(".feedback_open_password").val()
		});
		json = $.toJSON($(".formBuilder_example_form").formCreator("generate"));

		//我从这里开始改的啊~不要出Bug啊~！！啊~！！！
		// alterForm(id,"TEMPLATE",json,_self);
		// if($(".active_color").attr("shemeid")){
		// 	alterForm(id,"STYLEID",$(".active_color").attr("shemeid"));
		// }

        if (fieldValues == "") {
            fieldValues += '"TEMPLATE":' + json;
        } else {
            fieldValues += ',"TEMPLATE":' + json;
        }
        setPreValueList.push((function (a) {
            return function () {
                MKGlobal.preFormJSON = a;
            };
        })(json));



		if (fieldValues == "") {
			fieldValues += '"STYLE":"' + __saveLineGenerate() + '"';
		} else {
			fieldValues += ',"STYLE":"' + __saveLineGenerate() + '"';
		}
		MKGlobal.preFormSchemeInfo = __saveLineGenerate();

		// if (MKGlobal.formSchemeId) {
		// 	if (__saveLineGenerate() != MKGlobal.preFormSchemeInfo) {
		// 		if (fieldValues == "") {
		// 			fieldValues += '"STYLE":"' + __saveLineGenerate() + '"';
		// 		} else {
		// 			fieldValues += ',"STYLE":"' + __saveLineGenerate() + '"';
		// 		}
		// 	//	MKGlobal.preFormSchemeId = MKGlobal.formSchemeId;
		// 		setPreValueList.push((function (a) {
		// 			return function () {
		// 				MKGlobal.preFormSchemeInfo = a;
		// 			};
		// 		})(__saveLineGenerate()));
		// 	}
		// }

		if ($(".formStart_field").css("display") == "block") {
			startTime = $(".formStart_field").find("#form_startTime input").val();
			if (startTime != "") {
				startTime = startTime + ":00";
			}
			if (startTime != MKGlobal.formInfo.formControl.startDate) {
				if (fieldValues == "") {
					fieldValues += '"STARTDATETIME":"' + startTime + '"';
				} else {
					fieldValues += ',"STARTDATETIME":"' + startTime + '"';
				}
				//	MKGlobal.formInfo.formControl.startDate = startTime;
				setPreValueList.push((function (a) {
					return function () {
						MKGlobal.formInfo.formControl.startDate = a;
					};
				})(startTime));
			}
		} else {
			if (MKGlobal.formInfo.formControl.startDate != "") {
				if (fieldValues == "") {
					fieldValues += '"STARTDATETIME":""';
				} else {
					fieldValues += ',"STARTDATETIME":""';
				}
				//	MKGlobal.formInfo.formControl.startDate = "";
				setPreValueList.push((function (a) {
					return function () {
						MKGlobal.formInfo.formControl.startDate = a;
					};
				})(""));
			}
		}

		if ($(".formEndTime_field").css("display") == "block") {
			endTime = $(".formEndTime_field").find("#form_endTime input").val();
			if (endTime != "") {
				endTime = endTime + ":00";
			}
			if (endTime != MKGlobal.formInfo.formControl.stopDate) {
				if (fieldValues == "") {
					fieldValues += '"STOPDATETIME":"' + endTime + '"';
				} else {
					fieldValues += ',"STOPDATETIME":"' + endTime + '"';
				}
				//	MKGlobal.formInfo.formControl.stopDate = endTime;
				setPreValueList.push((function (a) {
					return function () {
						MKGlobal.formInfo.formControl.stopDate = a;
					};
				})(endTime));
			}
		} else {
			if (MKGlobal.formInfo.formControl.stopDate != "") {
				if (fieldValues == "") {
					fieldValues += '"STOPDATETIME":""';
				} else {
					fieldValues += ',"STOPDATETIME":""';
				}
				//	MKGlobal.formInfo.formControl.stopDate = "";
				setPreValueList.push((function (a) {
					return function () {
						MKGlobal.formInfo.formControl.stopDate = a;
					};
				})(""));
			}
		}

		if ($(".formEndMax_field").css("display") == "block") {
			endFeedbackNum = $(".formEndMax_field").find(".formEnd_feedbackNum input").val();
			if (endFeedbackNum != MKGlobal.formInfo.formControl.maxFeedback) {
				if (fieldValues == "") {
					fieldValues += '"MAX":"' + endFeedbackNum + '"';
				} else {
					fieldValues += ',"MAX":"' + endFeedbackNum + '"';
				}
				//	MKGlobal.formInfo.formControl.maxFeedback = endFeedbackNum;
				setPreValueList.push((function (a) {
					return function () {
						MKGlobal.formInfo.formControl.maxFeedback = a;
					};
				})(endFeedbackNum));
			}
		} else {
			if (MKGlobal.formInfo.formControl.maxFeedback != "") {
				if (fieldValues == "") {
					fieldValues += '"MAX":""';
				} else {
					fieldValues += ',"MAX":""';
				}
				//	MKGlobal.formInfo.formControl.maxFeedback = "";
				setPreValueList.push((function (a) {
					return function () {
						MKGlobal.formInfo.formControl.maxFeedback = a;
					};
				})(""));
			}
		}

		//这里增加 设置不可重复提交 字段
		if ($('#endFormSubmitOnce').attr("checked") == 'checked') {
			if (MKGlobal.formInfo.formSubmitOnce !== 1) {
				if (fieldValues == "") {
					fieldValues += '"SUBMITONCE":true';
				} else {
					fieldValues += ',"SUBMITONCE":true';
				}
				//	MKGlobal.formInfo.formSubmitOnce = 1;
				setPreValueList.push((function (a) {
					return function () {
						MKGlobal.formInfo.formSubmitOnce = a;
					};
				})(1));
			}
		} else {
			if (MKGlobal.formInfo.formSubmitOnce !== 0) {
				if (fieldValues == "") {
					fieldValues += '"SUBMITONCE":false';
				} else {
					fieldValues += ',"SUBMITONCE":false';
				}
			}
			//		MKGlobal.formInfo.formSubmitOnce = 0;
			setPreValueList.push((function (a) {
				return function () {
					MKGlobal.formInfo.formSubmitOnce = a;
				};
			})(0));
		}

		if(MKGlobal.formInfo.onlyWechat !== ($('#openFormOnlyByWeixin').attr('checked')=='checked'||false)){
			if(fieldValues == "") {
				fieldValues += '"ONLYWECHAT":'+($('#openFormOnlyByWeixin').attr('checked')=='checked'||false)+'';
			} else {
				fieldValues += ',"ONLYWECHAT":'+($('#openFormOnlyByWeixin').attr('checked')=='checked'||false)+'';
			}

			setPreValueList.push((function (a) {
				return function () {
					MKGlobal.formInfo.onlyWechat = a;
				};
			})($('#openFormOnlyByWeixin').attr('checked')=='checked'||false));
		}

		if(MKGlobal.formInfo.formRes !== ($('#endFormSubmitSawRes').attr('checked')=='checked'||false)){
			if(fieldValues == "") {
				fieldValues += '"PUBLICCHART":'+($('#endFormSubmitSawRes').attr('checked')=='checked'||false)+'';
			} else {
				fieldValues += ',"PUBLICCHART":'+($('#endFormSubmitSawRes').attr('checked')=='checked'||false)+'';
			}

			setPreValueList.push((function (a) {
				return function () {
					MKGlobal.formInfo.formRes = a;
				};
			})($('#endFormSubmitSawRes').attr('checked')=='checked'||false));
		}

		if(MKGlobal.formInfo.formResDetail !== ($('#endFormSubmitSawResDetail').attr('checked')=='checked'||false)){
			if(fieldValues == "") {
				fieldValues += '"OPENFEEDBACK":'+($('#endFormSubmitSawResDetail').attr('checked')=='checked'||false)+'';
			} else {
				fieldValues += ',"OPENFEEDBACK":'+($('#endFormSubmitSawResDetail').attr('checked')=='checked'||false)+'';
			}

			setPreValueList.push((function (a) {
				return function () {
					MKGlobal.formInfo.formResDetail = a;
				};
			})($('#endFormSubmitSawResDetail').attr('checked')=='checked'||false));
		}

        if(MKGlobal.formInfo.feedbackDetailPassword !== $('.feedback_open_password').val()){
            if(fieldValues == "") {
                fieldValues += '"OPENFEEDBACKPWD":""';
            } else {
                fieldValues += ',"OPENFEEDBACKPWD":"'+$('.feedback_open_password').val()+'"';
            }

            setPreValueList.push((function (a) {
                return function () {
                    MKGlobal.formInfo.feedbackDetailPassword = a;
                };
            })($('.feedback_open_password').val()));
        }

		if(MKGlobal.formInfo.formRandomCode !== ($('#endFormRandomCode').attr('checked')=='checked'||false)){
			if(fieldValues == "") {
				fieldValues += '"FEEDBACKCODE":'+($('#endFormRandomCode').attr('checked')=='checked'?1:0)+'';
			} else {
				fieldValues += ',"FEEDBACKCODE":'+($('#endFormRandomCode').attr('checked')=='checked'?1:0)+'';
			}

			setPreValueList.push((function (a) {
				return function () {
					MKGlobal.formInfo.formRandomCode = a;
				};
			})($('#endFormRandomCode').attr('checked')=='checked'||false));
		}

		if (($(".formStartError").css("visibility") == "hidden") && ($(".formEndError").css("visibility") == "hidden") && ($(".formEndMaxError").css("visibility") == "hidden")) {
			if(fieldValues != ""){
				alterForm(MKGlobal.formId, fieldValues, $(".active_color").attr("shemeid"), function (data) {
					for (var i in setPreValueList) {
						setPreValueList[i]();
					}
					callback();
				});
			} else {
				callback();
			}
		} else {
		}
	//}
})

function encodeValue(value) {
	var newValue = "";
	for (var i = 0; i < value.length; i++) {
		if (/^[\u4e00-\u9fa5]+/.test(value.charAt(i))) {
			newValue += getChineseSpell(value.charAt(i))[1];
		} else {
			newValue += value.charAt(i).toLowerCase();
		}
	}
	return newValue.replace(/[^a-zA-Z0-9]/g, '');
}

function simulationA(previewHref){
	$('body').append('<a id="simulationA" href="'+previewHref+'" target="_blank"><span id="simulationSpan">123</span></a>');
	$('#simulationSpan').click();
	$('#simulationA').remove();
}

var mgColorManager = (function () {
	var mgColor = '#ffffff',
		colorInfo = {};

	function getColorHSV(r, g, b) {
		var r = parseInt(('' + r).replace(/\s/g, ''), 10);
		var g = parseInt(('' + g).replace(/\s/g, ''), 10);
		var b = parseInt(('' + b).replace(/\s/g, ''), 10);

		r = r / 255;
		g = g / 255;
		b = b / 255;

		var minRGB = Math.min(r, Math.min(g, b)),
			maxRGB = Math.max(r, Math.max(g, b)),
			computedH, computedS, computedV;

		var d = (r == minRGB) ? g - b : ((b == minRGB) ? r - g : b - r);
		var h = (r == minRGB) ? 3 : ((b == minRGB) ? 1 : 5);

		computedH = 60 * (h - d / (maxRGB - minRGB));
		computedS = (maxRGB - minRGB) / maxRGB;
		computedV = maxRGB;
		return [computedH, computedS, computedV];
	}

	function HEX2RGB(hex) {
		// Expand shorthand form (e.g. "03F") to full form (e.g. "0033FF")
		var shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
		hex = hex.replace(shorthandRegex, function (m, r, g, b) {
			return r + r + g + g + b + b;
		});

		var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
		return result ? {
			r: parseInt(result[1], 16),
			g: parseInt(result[2], 16),
			b: parseInt(result[3], 16)
		} : null;
	}

	function COLORGARYLVL(r, g, b) {
		return parseInt(r) * 0.299 + parseInt(g) * 0.587 + parseInt(b) * 0.114;
	}

	function HSV2HEX(h, s, v) {
		var c = s * v,
			t = Math.abs((h / 60) % 2 - 1),
			x = c * (1 - t),
			m = v - c,
			r_t = 0, g_t = 0, b_t = 0;

		if (h >= 0 && h < 60) {
			r_t = c;
			g_t = x;
		} else if (h >= 60 && h < 120) {
			r_t = x;
			g_t = c;
		} else if (h >= 120 && h < 180) {
			b_t = x;
			g_t = c;
		} else if (h >= 180 && h < 240) {
			g_t = x;
			b_t = c;
		} else if (h >= 240 && h < 300) {
			r_t = x;
			b_t = c;
		} else if (h >= 300 && h < 360) {
			b_t = x;
			r_t = c;
		}

		function _toHEX(v) {
			return (Math.floor(v * 255)).toString(16);
		}

		return _toHEX(r_t + m) + _toHEX(g_t + m) + _toHEX(b_t + m); //[(r_t+m)*255, (g_t+m)*255, (b_t+m)*255];
	}


	return {
		setColor: function (str) {
			mgColor = str;
			var rgbC = HEX2RGB(str);
			colorInfo.R = rgbC.r;
			colorInfo.G = rgbC.g;
			colorInfo.B = rgbC.b;

			var hsvC = getColorHSV(colorInfo.R, colorInfo.G, colorInfo.B);

			colorInfo.H = Math.floor(hsvC[0]);
			colorInfo.S = Math.floor(hsvC[1] * 100);
			colorInfo.V = Math.floor(hsvC[2] * 100);
			return this;
		},
		getHSV2RGB: function (arrayHSV) {
			if(arrayHSV){
				return HSV2HEX(arrayHSV[0],arrayHSV[1],arrayHSV[2]);
			}
			return HSV2HEX(colorInfo.H, colorInfo.S / 100, colorInfo.V / 100);
		},
		getColorVal: function (colorStr, valueType) {
			var rgbC = HEX2RGB(colorStr),
				t = {};
			t.R = rgbC.r;
			t.G = rgbC.g;
			t.B = rgbC.b;

			var hsvC = getColorHSV(t.R, t.G, t.B);

			t.H = Math.floor(hsvC[0]);
			t.S = Math.floor(hsvC[1] * 100);
			t.V = Math.floor(hsvC[2] * 100);
			t.GY = COLORGARYLVL(t.R, t.G, t.B);
			if(valueType){
				return t[valueType];
			} else {
				return t;
			}

		},
		getColorGroup: function () {
			var brighten = colorInfo.S / 100,
				black = colorInfo.V / 100;

			var bkcolor = mgColor,
				bk_hover_color = HSV2HEX(colorInfo.H, (brighten - 0.08 > 0 ? brighten - 0.08 : 0), ((black - 0) + 0.14 < 1 ? (black - 0) + 0.14 : 1)),
				shadowcolor = HSV2HEX(colorInfo.H, ((brighten - 0.07 > 0) ? brighten + 0.07 : 0), (black - 0.06 > 0 ? (black - 0.06) : 0)),
				bordercolor = HSV2HEX(colorInfo.H, ((brighten + 0.04 < 1) ? brighten + 0.04 : 1), (black - 0.36 > 0 ? black - 0.36 : 0));

			shadowcolor = HSV2HEX(colorInfo.H, 0.52, 0.59);
			// bordercolor = HSV2HEX(colorInfo.H,0.60,0.37); 
			return {
				'BK': bkcolor,
				'BKH': bk_hover_color,
				'SD': shadowcolor,
				'BD': bordercolor
			};
		}
	};
})();