﻿

//===========================================================================
// From <=> WCF RESTful Data Connector
//---------------------------------------------------------------------------
//
//
//===========================================================================


(function ($) {

    $.fn.serialize = function (options) {
        var json = [];
        var form = $(this);
        $(form.serializeArray()).each(function (i, val) {
            if (val.name.match(/^[a-z].*/)) return;         // 小文字からはじまるnameは、シリアライズしない
            var name = val.name.split(".");
            var value = val.value.replace(/"/ig, "\\\"").replace(/\r\n/g, "\\r\\n").replace(/\r|\n/g, "\\r\\n");
            var idx = -1;
            var match = name[0].match(/(.*?)\[([0-9]*?)\]/);
            if (match != null && Number(match[2]) != NaN) {
                idx = Number(match[2]);
                name[0] = match[1];
            }

            if (val.name.indexOf("XROLE:") == 0) {          // XROLE属性は、.ネーム対象外
                name = [val.name];
            }

            $.each(json, function (i, obj) {
                if (obj["Key"] == name[0]) {
                    var vals = obj["Value"];
                    if (name.length > 1) {
                        if (vals[vals.length - 1][0]["Key"] == name[1]) {
                            vals[vals.length] = eval('([{"Key":"' + name[1] + '","Value":"' + value + '"}])');
                        } else {
                            var props = vals[vals.length - 1];
                            props[props.length] = eval('({"Key":"' + name[1] + '","Value":"' + value + '"})');
                        }
                    } else {
                        vals[vals.length] = eval('([{"Key":"*","Value":"' + value + '"}])');
                    }
                    name = null;
                    return false;
                }
            });

            if (name != null) {
                var obj = "";
                obj = '({ "Key":"' + ((name[0] == "") ? "*" : name[0]) + '", "Value":[[{"Key":"';
                obj += ((name.length > 1) ? name[1] : "*") + '","Value":"' + value + '"}]]})';
                json[json.length] = eval(obj);
            }

        });

        var token = null;
        try {
            token = eval("(" + $.cookie('token') + ")");
            token = token.token;
        } catch (exp) { token = ""; }

        json[json.length] = { "Key": "token", "Value": [[{ "Key": "*", "Value": token}]] };

        var xrole = "";
        if (XROLE != undefined) xrole = XROLE;
        json[json.length] = { "Key": "xrole", "Value": [[{ "Key": "*", "Value": xrole}]] };


        if (options != null) {
            json[json.length] = options;
/*            
            for (var obj in options) {
                alert(obj);
                json[json.length] = obj;
            }
*/            
        }


        return JSON.stringify(json);
    };


    $.fn.deserialize = function (obj, config) {
        var data = obj;
        form = this;

        if (obj == null || obj === undefined) {
            return form;
        }

        config = $.extend({ overwrite: true }, config);

        // check if data is an array, and convert to hash, converting multiple entries of 
        // same name to an array
        if (obj.constructor == Array) {
            data = {};
            for (var i = 0; i < obj.length; i++) {
                if (typeof data[d[i].name] != 'undefined') {
                    if (data[obj[i].name].constructor != Array) {
                        data[obj[i].name] = [data[obj[i].name], obj[i].value];
                    } else {
                        data[obj[i].name].push(obj[i].value);
                    }
                } else {
                    data[obj[i].name] = obj[i].value;
                }
            }
        }

        // now data is a hash. insert each parameter into the form
        $('input,select,textarea', form).each(function () {
            var val = [];

            if (this.name == null) return form;
            var key = "";
            if (this.name.indexOf("XROLE:") == 0 || this.name.indexOf("XQUERY:") == 0) {
                key = this.name;
            } else {
                key = this.name.replace(/([a-z0-9]+)([A-Z])([a-z0-9]+)/g, "$1.$2$3").toLowerCase();
            }
            var keys = key.split(".");
            var match = keys[0].match(/(.*?)\[([0-9]*?)\]/);
            var idx = -1;
            if (match != null && Number(match[2]) != NaN) {
                idx = Number(match[2]);
                keys[0] = match[1];
            }

            if (data[key] == undefined) {
                key = keys[0];
                if (data[key] == undefined) return form;
            }

            if (data[key].constructor == Number) {
                val = [data[key]];
            } else if (data[key].constructor == Array) {
                val = data[key];
            } else if (data[key].constructor == Object) {
                val = [data[key][keys[1]]];
            } else {
                if (data[key].indexOf("|") > -1) {
                    val = data[key].split("|");
                } else {
                    val = [data[key]];
                }
            }

            // Additional parameter overwrite
            if (config.overwrite === true || data[p]) {
                switch (this.type || this.tagName.toLowerCase()) {
                    case "radio":
                    case "checkbox":
                        this.checked = false;
                        for (var i = 0; i < val.length; i++) {
                            var sel = val[i];
                            if (typeof (sel) == "object") {
                                sel = val[i][(keys.length > 1) ? keys[1] : "*"];
                            }

                            this.checked |= (this.value != '' && sel == this.value);
                        }
                        $(this).change();
                        break;
                    case "select-multiple":
                    case "select":
                    case "select-one":
                        for (i = 0; i < this.options.length; i++) {
                            this.options[i].selected = false;
                            for (var j = 0; j < val.length; j++) {
                                var sel = val[j];
                                if (typeof (sel) == "object") {
                                    sel = val[j][(keys.length > 1) ? keys[1] : "*"];
                                }
                                this.options[i].selected |= (this.options[i].value != '' && this.options[i].value == sel);
                            }
                        }
                        $(this).change();
                        break;
                    case "button":
                    case "submit":
                    default:
                        if (idx > -1) {
                            val = val[idx][(keys.length > 1) ? keys[1] : "*"];
                        } else {
                            if (typeof (val[0]) == 'object') {
                                val = val[0][(keys.length > 1) ? keys[1] : "*"];
                            } else {
                                val = val.join(",");
                            }
                        }
                        if (val != undefined) {
                            this.value = val;
                            $(this).change();
                        }
                        break;
                }
            }
        });
        return form;
    };


})(jQuery);

//============================================================================
// FORM Query/Answer 操作
//----------------------------------------------------------------------------
//
//
//============================================================================

(function ($) {

	var QOBJS = {}; 						// qid <=> Query Object HashMap
	var AOBJS = {};							// answers

	$.fn.formWizard = function (options) {
		options = $.extend({
		}, options);

		var form = this;

		var steps = $(form).find("fieldset");
		var count = steps.size();


		$(form).before("<ul id='steps'></ul>");
		$(form).append( '<div style="text-align:center"><p id="xsubmit" class="xbutton submit"><a href="#"><span>回答を送信する</span></a></p></div>' );

		$('#xsubmit', this).hide();

		steps.each(function (i) {

			$(this).wrap("<div id='step" + i + "'></div>");
			$(this).append("<div id='step" + i + "errors' style='color:#F33; dispay:block; height:80px; margin: 4px 40px;'></div>");
			$(this).append("<p id='step" + i + "commands' style='margin-top:12px;'></p>");

			// 2
			var name = $(this).find("legend").html();
			$("#steps").append("<li id='stepDesc" + i + "'>Step " + (i + 1) + "<span>" + name + "</span></li>");

			if (i == 0) {
				createNextButton(i);
				selectStep(i);
			}
			else if (i == count - 1) {
				$("#step" + i).hide();
				createPrevButton(i);
				createNextButton(i);
			}
			else {
				$("#step" + i).hide();
				createPrevButton(i);
				createNextButton(i);
			}
		});

		function createPrevButton(i) {
			var stepName = "step" + i;
			$("#" + stepName + "commands").append("<a href='#' id='" + stepName + "Prev' class='prev'>< Back</a>");

			$("#" + stepName + "Prev").bind("click", function (e) {
				$("#" + stepName).hide();
				$("#step" + (i - 1)).show();
				$('#xsubmit', form).hide();
				selectStep(i - 1);
			});
		}

		function createNextButton(i) {
			var stepName = "step" + i;
			var selector = "#" + stepName + "Next";

			if(i < count - 1){				
				$("#" + stepName + "commands").append("<a href='#' id='" + stepName + "Next' class='next'>Next ></a>");
			}else{
				selector = "#xsubmit";
			}
			$(selector).bind("click", function (e) {

				$('#'+stepName+'errors').html("");
				var complete = true;
				var div = $('#'+stepName)[0];		
				$('input,select,textarea',  div).each( function(){
					if( $(this).attr('disabled') ) return true;							
					var val = "";
					switch( this.type || this.tagName.toLowerCase()){
					case "radio":
					case "checkbox":
						val = $('input[name=' + this.name + ']:checked').val();
						if( val == undefined || val == "" ){
							complete = false;
							return false;
						}
						break;
					case "select-multiple":
					case "select":
					case "select-one":
						var val = $('select[name=' + this.name + ']').val();
						if( val == "" || val == "選択してください" ){
							complete = false;
							return false;
						}
						break;
					case "button":
					case "submit":
					default:
//						alert ( "val = " + $(this).val() );
						break;

					}
					return true;
				});
				if( complete ){
					if( this.id == "xsubmit"){
						$('form#query').attr( "name", "createAnswer" );
						$('form#query').submit();
						return;
					}else{
						$("#" + stepName).hide();
						$("#step" + (i + 1)).show();
						if (i + 2 == count){
							$('#xsubmit', form).show();
						}
					}
					selectStep(i + 1);
				}else{
					$('#'+stepName+'errors').html( "※すべての項目を入力してください");
				}
			});
		}

		function selectStep(i) {
			$("#steps li").removeClass("current");
			$("#stepDesc" + i).addClass("current");
		}

	};


	/// inputの値取得
	///
	///

	$.fn.getVal = function(){
		if( $(this).attr('disalbe') ==='disable' ) return null;							
		var val = $(this).val();
		switch( this.type || this.tagName.toLowerCase()){
		case "radio":
		case "checkbox":
			val = $('input[name=' + this.name + ']:checked').val();
			if( val == undefined && val == "" ) val = "";
			break;
		case "select-multiple":
		case "select":
		case "select-one":
			var val = $('select[name=' + this.name + ']').val();
			if( val == "選択してください" ) val = "";
			break;
		case "button":
		case "submit":
		default:
			break;
		}
		return val;
	};

	$.fn.setQuery = function (options) {

		$('[xquery]').each(function () {
			try{
			var qid = $(this).attr('xquery').split("#");
			var opt = qid[0].split("|");
			var sep = opt[0].split(".");			
			var name = opt[0].replace( ".!", "." );
			qid[0] = sep[0];
			for( var i = 0; i < sep.length; i++ ){
				if( sep[i].indexOf( "!" ) == 0 ){
					qid[0] = sep[i].slice( 1 );
					break;
				}
			}
				
			switch (qid[1]) {
				case 'label':
					$(this).html('<label for="' + name + '">' + QOBJS[qid[0]]["question"] + '</label>');
					break;
				case 'checkbox':
				case 'radio':
					var html = '';
					var itype = qid[1];
					var sels = QOBJS[qid[0]]["selection"];

					$.each(sels, function (i, obj) {
						html += ('<div class="checkitem"><input type="' + itype + '" name ="XQUERY:' + name + '" value="');
						html += ((obj["value"] != undefined) ? obj["value"] : obj["option"]);
						html += ('" id ="' + name + '#' + i + '"/>');
						html += ('<label for="' + name + '#' + i + '">' + obj["option"] + '</label></div>');
					});
					$(this).html(html);
					break;
				case 'select':
					var html = '<select id="' + name + '" name="XQUERY:' + name + '">';
					html += '<option value="" >選択してください</option>';
					var sels = QOBJS[qid[0]]["selection"];
					$.each(sels, function (i, obj) {
						html += '<option value="';
						html += ((obj["value"] != undefined) ? obj["value"] : obj["option"]);
						html += '">';
						html += obj["option"];
						html += '</option>';
					});
					html += '</select>';
					$(this).html(html);
					break;
                        
				case 'text':
					var html = '';
					html += ('<input type="text" name ="XQUERY:' + name + '" value="" />');
					$(this).html(html);
					break;

			}
			$(this).removeAttr('xquery');
			if (opt.length > 1) {							// 条件処理
				var cnd = opt[1].match(/(.*?)\((.*?)\)/);
				var cnd2 = cnd[2].split(",");
				var target1 = $('[name="XQUERY:' + name + '"]');
				var target2 = $(this);
				var target3 = $('[for="' + name + '"]');
				$('[name="XQUERY:' + cnd[1] + '"]').change(function () {
					var sel = $(this).val();
					if( this.type == 'radio' || this.type == 'checkbox' ){
						sel = $('[name="'+this.name+'"]:checked').val();
					}
					if( $.inArray( sel, cnd2 ) > -1 ){
						target1.attr("disabled", "");
						target2.css("color", "#333");
						target3.css("color", "#333");
						change = true;
					}else {
						target1.attr("disabled", "disabled");
						target2.css("color", "#CCC");
						target3.css("color", "#CCC");
					}
				});
				target1.attr("disabled", "disabled");
				target2.css("color", "#CCC");
				target3.css("color", "#CCC");
			}
			}catch( e ){}

		});

	};

	///=========================================================================
	/// xquery属性を集めて　XQuery情報をロード
	///-------------------------------------------------------------------------
	///
	///=========================================================================

	$.fn.loadQuery = function () {
		var qids = [ { "Key":"IDS", "Value": [] }];
		var form = this;
		$('[xquery]', this).each(function () {
			var qid = $(this).attr('xquery').split("#");
			qid = qid[0].split("|");
			qid = qid[0].split(".");			// [parent qid].![qid]| = の場合のqid切り出し
			if (QOBJS[qid[0]] === undefined) {
				qids[0]["Value"][qids[0]["Value"].length] = eval( '( [ { "Key":"*", "Value":"' + qid[0] + '" } ] )' );
				QOBJS[qid[0]] = null;
			}
			if( qid.length > 1 &&  qid[1].indexOf("!") == 0 ){
				qid[1] = qid[1].slice( 1 );
				if (QOBJS[qid[1]] === undefined) {
					qids[0]["Value"][qids[0]["Value"].length] = eval( '( [ { "Key":"*", "Value":"' + qid[1] + '" } ] )' );
					QOBJS[qid[0]] = null;
				}
			}			

		});

        $.ajax({
            url: "/xobj/xquery",
            type: "POST",
            cache: false,
            async: false,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            data: JSON.stringify(qids),
            error: function (XMLHttpRequest, textStatus, errorThrown) {
            },
            success: function (json) {
				var objs = eval('(' + json + ')');
				$.each(objs, function (i, obj) {
					try{
						if (obj["answer.type"].indexOf("BOOL") > -1) {
							obj["selection"] = [{ option: "はい", value: "true" }, { option: "いいえ", value: "false"}];
						}
						QOBJS[obj["xid"]] = obj;
					}catch( e ){ 
					}
				});

				$(form).setQuery();
				$(form).formWizard();
            }
        });
	};

	///=========================================================================
	/// XAnswer情報をロード
	///-------------------------------------------------------------------------
	///
	///=========================================================================


	$.fn.loadAnswer = function(){
		var ctoken = $.cookie('token');
		var token = null;
		try{
			token = eval( "(" + ctoken + ")" );
		}catch( e ){}
		if( token == null ) return;
		var aids = [ { "Key":"IDS", "Value":[] }, { "Key":"token", "Value": [[{ "Key": "*", "Value": token.token }] ] } ];
		var form = this;
		$('input,select,textarea', form).each( function(){
			if( this.name.indexOf("XQUERY:") == 0 ){
				var ids = this.name.substring(7).split("|");
				$.each( ids, function( idx, val ){
					var xid = val.split(".");
					for( var i=0; i < aids[0]["Value"].length; i++ ){
						if( xid[0] == aids[0]["Value"][i][0]["Value"] ){
							xid[0] = null;
							break;
						}
					}
					if( xid[0] != null ){
						aids[0]["Value"][aids[0]["Value"].length] = eval( '( [ { "Key":"*", "Value":"' + xid[0] + '" } ] )' );
					}
				});	
			}

		});

        $.ajax({
            url: "/xobj/xanswer",
            type: "POST",
            cache: false,
            async: false,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            data: JSON.stringify(aids),
            error: function (XMLHttpRequest, textStatus, errorThrown) {
            },
            success: function (json) {
				AOBJS = eval('(' + json + ')');
				$(form).deserialize(AOBJS);

            }
        });

	};









})(jQuery); 













//============================================================================
// 複数形<->単数形　変換
//----------------------------------------------------------------------------
//
//
//============================================================================

(function ($) {

    var UNI = [
                    'deer', 'fish', 'measles', 'ois', 'pox', 'rice', 'sheep', 'Amoyese', 'bison', 'bream',
                    'buffalo', 'cantus', 'carp', 'cod', 'coitus', 'corps', 'diabetes', 'elk', 'equipment',
                    'flounder', 'gallows', 'Genevese', 'Gilbertese', 'graffiti', 'headquarters', 'herpes',
                    'information', 'innings', 'Lucchese', 'mackerel', 'mews', 'moose', 'mumps', 'news', 'nexus',
                    'Niasese', 'Pekingese', 'Portuguese', 'proceedings', 'rabies', 'salmon', 'scissors', 'series',
                    'shears', 'siemens', 'species', 'testes', 'trousers', 'trout', 'tuna', 'whiting', 'wildebeest',
                    'Yengeese'
            ];

    var PLRULES = {
        '/(s)tatus$/i': 'RegExp.$1+"tatuses"',
        '/^(ox)$/i': 'RegExp.$1+"en"',
        '/([m|l])ouse$/i': 'RegExp.$1+"ice"',
        '/(matr|vert|ind)ix|ex$/i': 'RegExp.$1+"ices"',
        '/(x|ch|ss|sh)$/i': 'RegExp.$1+"es"',
        '/(r|t|c)y$/i': 'RegExp.$1+"ies"',
        '/(hive)$/i': 'RegExp.$1+"s"',
        '/(?:([^f])fe|([lr])f)$/i': 'RegExp.$1+RegExp.$2+"ves"',
        '/(.*)sis$/i': 'RegExp.$1+"ses"',
        '/([ti])um$/i': 'RegExp.$1+"a"',
        '/(buffal|tomat)o$/i': 'RegExp.$1+"oes"',
        '/(bu)s$/i': 'RegExp.$1+"ses"',
        '/(alias)/i': 'RegExp.$1+"es"',
        '/(octop|vir)us$/i': 'RegExp.$1+"i"',
        '/(.*)s$/i': 'RegExp.$1+"s"',
        '/(.*)/i': 'RegExp.$1+"s"'
    };

    var PLMAP = {
        'atlas': 'atlases', 'child': 'children',
        'corpus': 'corpuses', 'ganglion': 'ganglions',
        'genus': 'genera', 'graffito': 'graffiti',
        'leaf': 'leaves', 'man': 'men',
        'money': 'monies', 'mythos': 'mythoi',
        'numen': 'numina', 'opus': 'opuses',
        'penis': 'penises', 'person': 'people',
        'sex': 'sexes', 'soliloquy': 'soliloquies',
        'testis': 'testes', 'woman': 'women',
        'move': 'moves'
    };

    var SGRULES = {
        '/(s)tatuses$/i': 'RegExp.$1+"tatus"',
        '/^(ox)en$/i': 'RegExp.$1',
        '/([m|l])ice$/i': 'RegExp.$1+"ouse"',
        '/(matr)ices$/i': 'RegExp.$1+"ix"',
        '/(vert|ind)ices$/i': 'RegExp.$1+"ex"',
        '/(cris|ax|test)es$/i': 'RegExp.$1+"is"',
        '/(x|ch|ss|sh)es$/i': 'RegExp.$1',
        '/(r|t|c)ies$/i': 'RegExp.$1+"y"',
        '/(movie)s$/i': 'RegExp.$1',
        '/(hive)s$/i': 'RegExp.$1',
        '/([^f])ves$/i': 'RegExp.$1+"fe"',
        '/([lr])ves$/i': 'RegExp.$1+"f"',
        '/(analy|ba|diagno|parenthe|synop|the)ses$/i': 'RegExp.$1+"sis"',
        '/([ti])a$/i': 'RegExp.$1+"um"',
        '/(buffal|tomat)oes$/i': 'RegExp.$1+"o"',
        '/(bu)ses$/i': 'RegExp.$1+"s"',
        '/(alias)es/i': 'RegExp.$1',
        '/(octop|vir)i$/i': 'RegExp.$1+"us"',
        '/(.*)s$/i': 'RegExp.$1',
        '/(.*)/i': 'RegExp.$1'
    };


    var SGMAP = {
        'atlases': 'atlas', 'children': 'child',
        'corpuses': 'corpus', 'ganglions': 'ganglion',
        'genera': 'genus', 'graffiti': 'graffito',
        'leaves': 'leaf', 'men': 'man',
        'monies': 'money', 'mythoi': 'mythos',
        'numina': 'numen', 'opuses': 'opus',
        'penises': 'penises', 'people': 'person',
        'sexes': 'sex', 'soliloquies': 'soliloquy',
        'testes': 'testis', 'women': 'woman',
        'moves': 'move'
    };

    $.fn.pluralize = function (word) {
        var wordl = word.toLowerCase();
        for (var elm in UNI) {
            if (wordl == elm) return word;
        }
        for (var key in PLMAP) {
            if (wordl == key) return PLMAP[key];
        }
        for (var key in PLRULES) {
            try {
                var robj = eval("new RegExp(" + key + ");");
                if (word.match(robj)) {
                    return word.replace(robj, eval("(" + PLRULES[key] + ")"));
                }
            } catch (e) {
//                alert(e.description);
            }
        }
        return word;
    };

    $.fn.singularize = function (word) {
        var wordl = word.toLowerCase();
        for (var elm in UNI) {
            if (wordl == UNI) return word;
        }
        for (var key in SGMAP) {
            if (wordl == key) return SGMAP[key];
        }
        for (var key in SGRULES) {
            try {
                var robj = eval("new RegExp(" + key + ");");
                if (word.match(robj)) {
                    return word.replace(robj, eval("(" + SGRULES[key] + ")"));
                }
            } catch (e) {
//                alert(e.description);
            }
        }
        return word;
    };

})(jQuery);


