/*
 * Form tools
 *
 * Copyright (c) 2009 Artemy Nikolsky (tema@nopublic.ru)
 *
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 *
 * Date: 2009-07-06
 *
 */

(function ($) {
    var dataCache = [];

    $.fn.nValidate = function (options) {
        var defaults = {
            controllerName:null,
            formName:null,
            rules:null
        };

        var  settings = $.extend({}, defaults, options);

        var validators = {
            required:function(val){
                if(val.length() = 0){
                    return false;
                }
                return  true;
            },
            min_length:function(val){

            }

        }

        var jForm = $('#'+settings.controllerName +'_'+ settings.formName);

        function todoValidate(id){ //TODO no AJAX
            console.log(id)
            for(i in  settings.rules){
                if( typeof validators[settings.rules[i].rule]  == 'function'){
                    validators[settings.rules[i].rule]()
                }
            }
            console.log()
        }


        parsJSON = function() {var r="(?:-?\\b(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?(?:[eE][+-]?[0-9]+)?\\b)",k='(?:[^\\0-\\x08\\x0a-\\x1f"\\\\]|\\\\(?:["/\\\\bfnrt]|u[0-9A-Fa-f]{4}))';k='(?:"'+k+'*")';var s=new RegExp("(?:false|true|null|[\\{\\}\\[\\]]|"+r+"|"+k+")","g"),t=new RegExp("\\\\(?:([^u])|u(.{4}))","g"),u={'"':'"',"/":"/","\\":"\\",b:"\u0008",f:"\u000c",n:"\n",r:"\r",t:"\t"};function v(h,j,e){return j?u[j]:String.fromCharCode(parseInt(e,16))}var w=new String(""),x=Object.hasOwnProperty;return function(h,
j){h=h.match(s);var e,c=h[0],l=false;if("{"===c)e={};else if("["===c)e=[];else{e=[];l=true}for(var b,d=[e],m=1-l,y=h.length;m<y;++m){c=h[m];var a;switch(c.charCodeAt(0)){default:a=d[0];a[b||a.length]=+c;b=void 0;break;case 34:c=c.substring(1,c.length-1);if(c.indexOf("\\")!==-1)c=c.replace(t,v);a=d[0];if(!b)if(a instanceof Array)b=a.length;else{b=c||w;break}a[b]=c;b=void 0;break;case 91:a=d[0];d.unshift(a[b||a.length]=[]);b=void 0;break;case 93:d.shift();break;case 102:a=d[0];a[b||a.length]=false;
b=void 0;break;case 110:a=d[0];a[b||a.length]=null;b=void 0;break;case 116:a=d[0];a[b||a.length]=true;b=void 0;break;case 123:a=d[0];d.unshift(a[b||a.length]={});b=void 0;break;case 125:d.shift();break}}if(l){if(d.length!==1)throw new Error;e=e[0]}else if(d.length)throw new Error;if(j){var p=function(n,o){var f=n[o];if(f&&typeof f==="object"){var i=null;for(var g in f)if(x.call(f,g)&&f!==n){var q=p(f,g);if(q!==void 0)f[g]=q;else{i||(i=[]);i.push(g)}}if(i)for(g=i.length;--g>=0;)delete f[i[g]]}return j.call(n,
o,f)};e=p({"":e},"")}return e}}();


        function validate(name,val,el){
            if(name == 'password2'){
                var jForm = $('#'+settings.controllerName +'_'+ settings.formName);
//                console.log(el.parent(),settings.formName,settings.controllerName,jForm,$('input#password2errorBox').parents('form'));
                if($('input[name=password2]').val().length = 0){
                    return '<div id="password2errorBox"><div class="error"><div class="txt">This information is required</div></div></div>'
                }else if($('input[name=password2]').val() != $('input[name=password]',jForm).val()){
                    return '<div id="password2errorBox"><div class="error"><div class="txt">Please verify your password again</div></div></div>'
                } else{
                    return '';
                }
            }else{
                var postData = {}

                postData[name] = val;

                return parsJSON($.ajax({
                    'url' : '/ajax/validate/' + settings.controllerName +'/'+ settings.formName,
                    'type': "POST",
                    'dataType' : 'json',
                    'data' : postData,
                    'async' : false

                }).responseText);
            }



        }
        
        function doValidate(el){
            var valid = validate(el.attr('name'),el.val(),el);
//            console.log(valid,valid.length)
            if(!valid.valid){
//                console.log('#'+el.attr('name')+'errorBox')
                $('#'+el.attr('name')+'errorBox',jForm).html(valid.msg);

                el.addClass('errorInput');
            }else{
//                console.log('clean')
                el.removeClass('errorInput');
                $('#'+el.attr('name')+'errorBox',jForm).html('');
            }
        }



        return this.each(function () {

            var jElm = $(this);

            jElm.blur(function(){
                doValidate($(this));
            });
//                    .focus(function(){
//                if(jElm.val() == jElm.attr('hint')){
//                    jElm.val('').removeClass(settings.hintClass);
//                }
//            })
//            if(jElm.val() == '' || jElm.val() == jElm.attr('hint')){
//                jElm.val(jElm.attr('hint')).addClass(settings.hintClass);
//            }
        });
        $("form#" +settings.controllerName+'_'+ settings.formName).submit(function(){
            return false;
        });
    };
})(jQuery);


/**
 * input hint
 *
 * before: <input hint="search" >
 * $('input[hint]').jHint({hintClass:'inputHint'})
 * after:
 * <input hint="search" value="search" class="inputHint">
 *
 */

(function ($) {
    var dataCache = [];

    $.fn.jHint = function (options) {
        var defaults = {
            'hintClass' : 'inputHint'
        };

        var  settings = $.extend({}, defaults, options);

        return this.each(function () {
            var jElm = $(this);

            jElm.blur(function(){
                if(jElm.val() == ''){
                    jElm.val(jElm.attr('hint')).addClass(settings.hintClass);
                }
            }).focus(function(){
                if(jElm.val() == jElm.attr('hint')){
                    jElm.val('').removeClass(settings.hintClass);
                }
            })
            if(jElm.val() == '' || jElm.val() == jElm.attr('hint')){
                jElm.val(jElm.attr('hint')).addClass(settings.hintClass);
            }
        });
        $("form").submit(function(){
            $('form > input[hint]').each(function(i,v){
                 if($(v).val() == $(v).attr('hint')){
                    $(v).val('');
                 }
            });
        });
    };
})(jQuery);


(function ($) {
    var dataCache = [];

    $.fn.jSuggest = function (options) {
        var defaults = {

            'dataContainerClass' : 'suggest',
            'data' : null,
            'url' : null,
            'delay' : 0,
            'separator' : false,
             minLength:0,
             autoShow:false,
             urlParams: {},
             autoComplite:false,
             multiSelect:false,
             showNotFindMsg:false,
             closeBox:'<span>Close</span>',
             callBack:false
        };

        var  settings = $.extend({}, defaults, options);

        return this.each(function () {
            var jElm = $(this);
            var elm = this;
            var isShow = false;
            var selected = [];
            var cache = {};

            var suggestBox = document.createElement('div');

            function setPos(suggestBox){
                var offset = jElm.offset();
                console.log(offset.top,jElm.scrollTop());
                $(suggestBox).css({
                                top:offset.top + jElm.height() + 3  +'px',
                                left:offset.left  + 'px',
                                width:jElm.width() + 'px'});
            }

            setPos(suggestBox);

            $(suggestBox).addClass(settings.dataContainerClass).append('<div class="list"></div><div class="close">'+settings.closeBox+'</div>').hide();
            $('div.close span',suggestBox).click(function(){
                jElm.next('div').hide();
                isShow=false;
            });
            jElm.after(suggestBox);


            function close(){
                jElm.next('div').hide();
                isShow = false;
            }
            jElm.focus(function(e){
          //  console.log(isShow,settings.autoShow());
                if(!isShow){
                    if(typeof settings.autoShow == 'function'){
                        if(settings.autoShow(jElm.val())){
                            showSuggest()
                        }
                    }else if(settings.autoShow){
                            showSuggest()

                    }
                }
            });

            jElm.blur(function(){close;});

            function isAutoShow(){
                if(typeof settings.autoShow == 'function'){
                        if(settings.autoShow(jElm.val())){
                            return true;
                        }
                }else if(settings.autoShow){
                    return true;

                }
                return false;
            }

            function showSuggest(){
                var jSuggestBox = jElm.next('div');
                var jSuggestList = jSuggestBox.children('div.list');
                var suggestList = [];
                var val = jElm.val().toLowerCase();

                jSuggestList.html('');


                if(settings.multiSelect && val.indexOf(settings.separator) != -1){
                    var strongVal = val.substring(0,val.lastIndexOf(settings.separator)+1)
                    val = $.trim(val.substring(val.lastIndexOf(settings.separator)+1) )
                    jElm.data('val',strongVal + ' ');
                }else{
                    jElm.data('val','');
                }

                if(val.length > 0 || val.length > settings.minLength || settings.autoShow){
                    if(settings.url != null){
                        suggestList = url(val);
                    }else if( typeof settings.callBack == 'function'){
                        suggestList = settings.callBack (val);
                    }else{
                        suggestList = settings.data
                    }
                    $.each(suggestList,function(i,v){
                        if(v.txt.toString().toLowerCase().indexOf(val.toString()) == 0){
                            jSuggestList.append($(document.createElement("div")).text(v.txt));
                        }

                    })



                    jSuggestList.children('div').click(function(){jElm.val(jElm.data('val') + $(this).text() );jSuggestBox.hide();})

                    if(jSuggestList.html() != ''){
                        setPos(suggestBox);
                        jSuggestBox.show();
                        isShow = true;
                    }else if(isAutoShow()){
                        showSuggest()
                    }else{
                        jSuggestBox.hide();
                        isShow = false;
                    }

                }
            }

            function url(pattern){
                var params = {}, responseObj = {};

                $.each(cache,function(i,v){
                    if(v.txt.toString().toLowerCase().indexOf(pattern.toString()) == 0){
                        responseObj[i] = v
                    }
                })
               // console.log( responseObj )
                if(!responseObj[1]){
                $.extend(params,settings.urlParams )
    //console.log(settings.urlParams.countryId,'=1')
                    $.each(settings.urlParams,function(i,v){if(typeof v == 'function'){
                        params[i] = settings.urlParams[i]()
                    }});
    //console.log(params.countryId,'=2');
                    params.pattern = pattern;

                    $.ajax({
                        'url' : '/ajax/suggest/' + settings.url,
                        'dataType' : 'json',
                        'data' : params,
                        'async' : false,
                        'success' : function (response) {
                            responseObj =  response;
                        }
                    });
                    cache = responseObj;
                }
                return responseObj;

            }


            function keyup(e){
                if ((e.which != 38 &&  e.which != 40 && e.which != 13 ) ) {
                    showSuggest()
                }
            }

            jElm.keyup(function (e){keyup(e)});

            jElm.keydown(function (e) {
                if ((e.which == 38 || e.which == 40 || e.which == 13 ) && isShow) {
//                    jElm.unbind('keyup');
//                    console.log(jElm.keyup,'ssd')
                    jSuggestList = jElm.next('div').children('div.list');

                    if(e.which == 40 ){
                        if(jSuggestList.children('div.selected').size() == 0){
                            $('div:first',jSuggestList).addClass('selected');
                        }else{
                            if($('div.selected',jSuggestList).next().size() == 0){
                                $('div.selected',jSuggestList).removeClass('selected');
                                $('div:first',jSuggestList).addClass('selected');
                            }else{
                                $('div.selected',jSuggestList).removeClass('selected').next().addClass('selected');
                            }
                        }
                    }else if(e.which == 38){
                       if(jSuggestList.children('div.selected').size() == 0){
                            $('div:last',jSuggestList).addClass('selected');
                        }else{
                            if($('div.selected',jSuggestList).prev().size() == 0){
                                $('div.selected',jSuggestList).removeClass('selected');
                                $('div:last',jSuggestList).addClass('selected');
                            }else{
                                $('div.selected',jSuggestList).removeClass('selected').prev().addClass('selected');
                            }

                        }
                    }
                    jElm.val(jElm.data('val') + $('div.selected',jSuggestList).text());
                    if(e.which == 13){
                        if(isAutoShow()){
                            showSuggest()
                        }else{
                            close();
                        }
                    }
                    return false;

                }

            });
            if(settings.autoShow){
                jElm.focus(
                function(){
                    showSuggest();
                }).blur(function(){
                    close();
                });
            }

        });
    };
})(jQuery);
