var SysHelp = {
    selectAjax: function (src, target, url, fn) {
        function jqObj(elm) {
            if (typeof elm == 'string' && elm.substr(0, 1) != '#')
                elm = '#' + elm;
            return $(elm);
        }

        src = jqObj(src);
        fn = fn || function () { };

        src.change(function () {
            var selectValue = $(this).val();
            target = jqObj(target);            
            target.children().each(function () {
                var v = $(this).val();
                if (v != '') {
                    $(this).remove();
                }
            });
            $.uniform.update(target);
            // target.change();

            if (selectValue) {
                $.get(url + encodeURIComponent(selectValue), function (rs) {
                    target.append(rs);
                    fn(src, target);
                    target.change();
                });
            } else {
                fn(src, target);
                target.change();
            }
        });
    },
    selectOther: function (selectElm, otherElm, valElm) {
        selectElm = $(selectElm), otherElm = $(otherElm), valElm = $(valElm);

        selectElm.change(function () {
            if (!$(this).val())
                otherElm.closest('div').fadeIn();
            else
                otherElm.closest('div').fadeOut();
        });

        var v = valElm.val();
        if (v) {
            var options = selectElm.get(0).options;
            var flag = false;
            for (var i = 0, len = options.length; i < len; ++i) {
                if (options[i].value == v) {
                    flag = true;
                    options[i].selected = true;
                }
            }
            if (!flag) {
                selectElm.val('');
                otherElm.val(v);
            }
        }
        selectElm.trigger('change');
    },
    checkbox: function (outerElm) {
        $(outerElm).each(function () {
            var checkElms = $(this).find(':checkbox');
            var allElm = checkElms.filter('.all');
            checkElms = checkElms.not('.all');
            var valElm = $(this).next();

            function setVals() {
                var vals = [];
                checkElms.each(function () {
                    if (this.checked)
                        vals.push(this.value);
                });
                valElm.val(vals.join());
            }

            allElm.click(function () {
                $.uniform.update(checkElms.prop('checked', this.checked));
                setVals();
            });

            var selectedVals = valElm.val().split(',');
            checkElms.each(function () {
                $(this).click(function () {
                    if (this.checked) {
                        if (checkElms.filter(':not(:checked)').length == 0)
                            $.uniform.update(allElm.prop('checked', true));
                    } else {
                        if (allElm.prop('checked')) {
                            $.uniform.update(allElm.prop('checked', false));
                        }
                    }

                    setVals();
                });

                if ($.inArray(this.value, selectedVals) != -1)
                    this.checked = true;
            });

            if (checkElms.filter(':not(:checked)').length == 0)
                allElm.prop('checked', true);
        });
    },
    radio: function (outerElm, fn) {
        fn = fn || function () { };

        $(outerElm).each(function () {
            var $this = $(this);
            var v = $.trim($this.next().val());
            $this.find(':radio').each(function () {
                if (this.value == v) {
                    this.checked = true;
                    fn.call($this.get(0), this.value);
                }

                $(this).click(function () {
                    $this.next().val(this.value);
                    fn.call($this.get(0), this.value);
                });
            });
        });
    },
    enterPress: function (element, func) {
        $(element).keydown(function (event) {
            if (event.keyCode == 13) {
                if ($(event.target).is('textarea'))
                    return;

                event.preventDefault();
                func.apply(this);
            }
        });
    },
    showElementError: function (element, msg, isSlide, position) {
        $(element).validationEngine('showPrompt', msg, 'error', position, true);
        $('div.formError').click(function () {
            $(this).fadeOut('normal', function () { $(this).remove(); });
        });

        if (isSlide) {
            $body = (window.opera) ? (document.compatMode == 'CSS1Compat' ? $('html') : $('body')) : $('html,body');
            $body.animate({ scrollTop: $('div.formError:first').offset().top }, 500);
        }
    },
    dropzone: function (outerElm, type, path) {
        function getImgHtml(img) {
            var html =
                '<div class="col-full-100 outer">' +
                '   <div class="itemBox ImageFlex">' +
                '       <div class="defaultWrap">' +
                '           <div><img src="' + $webPath + '/Upload/' + img + '" /></div>' +
                '       </div>' +
                '   </div>' +
                '   <div class="adminbox">' +
                '       <ul>' +
                '           <li style="float:right;"><a class="btn-black cube circle btn-del tooltip tooltipstered"><i class="fa fa-trash-o"></i></a></li>'
            '       </ul>' +
            '   </div>' +
            '</div>';
            return html;
        }

        $(outerElm).each(function () {
            var acceptedFiles = 'image/*';
            if (type == 'doc')
                acceptedFiles = '.zip,.rar,.txt,.doc,.docx,.xls,.xlsx,.ppt,.pptx,.pdf,.jpeg,.jpg,.png,.gif';

            var $this = $(this);

            var dropz = new Dropzone('#' + $this.prop('id'), {
                url: $basePath + '/Common/fileUpload.ashx?path=' + encodeURIComponent(path) + '&type=' + (type || 'image'),
                acceptedFiles: acceptedFiles,
                uploadMultiple: false,
                maxFiles: 1,
                dictRemoveFile: "Delete the file",
                dictCancelUpload: "Cancel the upload",
                dictDefaultMessage: "Drag and drop File here",
                init: function () {
                    this.on('success', function (file, rs) {
                        $this.find('input').val(rs);
                        $this.children('.dropzone').hide();
                        $this.children('img').remove();

                        if (type == 'image') {
                            var newImg = $(getImgHtml(rs));
                            $this.append(newImg);
                            newImg.click(function () {
                                $(this).parent().click();
                            });
                            newImg.find('a.btn-del').click(function (e) {
                                e.stopPropagation();
                                $(this).closest('div.outer').remove();
                                $this.children('.dropzone').show();
                                $this.find('input').val('');
                            });
                        }

                        dropz.removeFile(file);
                        dropz.options.maxFiles = 1;
                    });
                }
            });

            var img = $this.find('input').val();
            if (img) {
                $this.children('.dropzone').hide();

                if (type == 'image') {
                    var newImg = $(getImgHtml(img));
                    $this.append(newImg);
                    newImg.click(function () {
                        $(this).parent().click();
                    });
                    newImg.find('a.btn-del').click(function (e) {
                        e.stopPropagation();
                        $(this).closest('div.outer').remove();
                        $this.children('.dropzone').show();
                        $this.find('input').val('');
                    });
                }
            }
        });
    },
    dropzoneImages: function (btnElms, path, fn) {
        fn = fn || function () { };

        $(btnElms).each(function () {
            var dropz = new Dropzone('#' + $(this).next().prop('id'), {
                url: $basePath + '/Common/fileUpload.ashx?path=' + encodeURIComponent(path) + '&type=image',
                acceptedFiles: 'image/*',
                uploadMultiple: false,
                maxFiles: 200,
                init: function () {
                    this.on('success', function (file, rs) {
                        fn(rs);

                        dropz.removeFile(file);
                        dropz.options.maxFiles = 200;
                    });
                }
            });
            $(this).click(function () {
                $(this).next().click();
            });
        });
    },
    switchShow: function (afterFn) {
        afterFn = afterFn || function () { };
        $('input[data-hide],input[data-show]').each(function () {
            var $this = $(this);
            function show(elms) {
                var animal = $this.attr('data-animal') || 'slide';
                if (animal == 'slide')
                    elms.slideDown();
                else if (animal == 'fade')
                    elms.fadeIn();

                elms.find('input[data-hide]:checked').each(function () {
                    $($(this).attr('data-hide')).hide();
                });
            }

            function hide(elms) {
                var animal = $this.attr('data-animal') || 'slide';
                if (animal == 'slide')
                    elms.slideUp();
                else if (animal == 'fade')
                    elms.fadeOut();
            }

            var hideElms = $($this.attr('data-hide'));
            var showElms = $($this.attr('data-show'));

            if (this.checked) {
                hideElms.hide();
                showElms.show();
                afterFn($this.attr('data-show'), $this.attr('data-hide'), true);
            }

            $this.click(function () {
                if (this.checked) {
                    hide(hideElms);
                    show(showElms);
                } else {
                    show(hideElms);
                    hide(showElms);
                }
                afterFn($this.attr('data-show'), $this.attr('data-hide'), this.checked);
            });
        });
    },
    iframe: function (url, width, height) {
        $('div.formError').remove();
                
        width = width || '80%';
        height = height || '80%';
        
        $.colorbox({
            iframe: true,
            href: url,
            width: width,
            height: height,
            onOpen: function () {
                //$('#colorbox').addClass("inlinBox");
            }
        });
    },
    iframeButton: function (btnElms) {
        $(btnElms).each(function () {
            var $this = $(this);
            var width = $this.attr('data-width') || '80%';
            var height = $this.attr('data-height') || '80%';

            $this.colorbox({
                iframe:true,
                width:width,
                height:height,
                onOpen:function(){
                    //$('#colorbox').addClass("inlinBox");
                }
            });
        });
    },
    queryString: function (key) {
        var querys = location.search;
        if (!querys)
            return null;

        key = key.toLowerCase();
        querys = querys.substring(1).split('&');

        for (var i = 0, len = querys.length; i < len; ++i) {
            var q = $.trim(querys[i]);
            if (!q)
                continue;

            q = q.split('=');
            if (q[0].toLowerCase() == key) {
                q.shift();
                return $.trim(decodeURIComponent(q.join('=')));
            }
        }
    }
};