/**
 * 艾迪书院前端JS.UI公共类包
 *
 * @package JS.UI
 * @author 纯粹误会<44922032@qq.com>
 * @version $Id: ui.src.js 1499 2011-02-18 10:40:14Z wujie $
 * @copyright (c) 2010, 艾迪书院<www.egshuyuan.com>
 */

$(function(){
    //插件
    jQuery.fn.extend({
        //-- form required
        required: function() {
            try{
                var isOk = false;
                var _this = this;
                $(_this).find('.required').each(function(){
                    if(isOk || $(this).attr('disabled') || 'none' == $(this).css('display')){
                        return;
                    }
                    if('input' == $(this).attr('tagName').toLowerCase() ){
                        var type = $(this).attr('type').toLowerCase();
                        if('radio' == type || 'checkbox' == type){
                            var val = '';
                            $(_this).find('input[name=' + $(this).attr('name') + ']').each(function(){
                                if($(this).attr('checked')){
                                    val += 1;
                                }
                            });
                            if('' == val){
                                $(this)[0].focus();
                                isOk = true;
                            }
                            return;
                        }
                    }
                    if('' == $(this).val() || $(this).attr('rel') == $(this).val()){
                        $(this)[0].focus();
                        isOk = true;
                    }
                });
                return isOk;
            }
            catch(e){
                alert('required : ' + e);
                return false;
            }
        },
        //-- form serializeKeyValue
        serializeKeyValue: function() {
            var params = {};
            try{
                var values = $(this).serializeArray();
                for(var i = 0, l = values.length; i < l; i++){
                    params[values[i].name] = values[i].value;
                }
            }
            catch(e){
                alert('serializeKeyValue : ' + e);
                return params;
            }
            return params;
        },
        //-- my post
        myPost:function(fn){
            if($(this).required()){
              return false;
            }
            try{
                var url = $.postfix($(this).attr('action'), true);
                var params = $(this).serializeKeyValue();
                var _this = this;
                $.post(
                    url,
                    params,
                    function(res){
                        $.api(res, fn, _this);
                    }
                );
                return false;
            }
            catch(e){
                alert('myPost : ' + e);
                return false;
            }
        },
        //-- my get
        myGet: function(fn) {
            try{
                var url = $.postfix($(this).attr('href'), true);
                var _this = this;
                $.get(
                    url,
                    null,
                    function(res){
                        $.api(res, fn, _this);
                    }
                );
                return false;
            }
            catch(e){
                alert('myGet : ' + e);
                return false;
            }
        },
        //-- flasher
        flasher: function(){
          var _this = $(this);
          if(!_this[0])return;
          var sw = 0;
          if (document.all && $.browser.msie && 7 <= $.browser.version  ){
              _this.find('img').css({'cssText': 'filter: progid:dximagetransform.microsoft.wipe(gradientsize=1.0,wipestyle=4, motion=forward);'});
          }
          var flasherList = _this.find('ul li');
          var flasherNums = _this.find('.num');
          var flasherLen = flasherList.length;
          for(var i = 0; i < flasherLen; i++){
            flasherNums.append("<a" +( 0 == i ? ' class="cur"' : '' ) + ">" + ( i + 1 ) + "</a>");
          }
          var flasherLinks = _this.find('.num a');
          flasherLinks.mouseover(function(){
            sw = flasherLinks.index(this);
            myShow(sw);
          });
          function myShow(i){
            //flasherLinks.eq(i).addClass("cur").siblings("a").removeClass("cur");
            flasherLinks.removeClass("cur");
            flasherLinks.eq(i).addClass("cur");
            if (document.all){
                try{
                    var obj = flasherList.eq(i).find('img')[0].filters[0];
                    if(obj){
                        obj.Apply();
                        obj.Play(duration = 2);
                    }
                }
                catch(e){
                }
            }
            flasherList.eq(i).stop(true,true).fadeIn(600).siblings("li").fadeOut(600);
          }
          function shower(){
               myShow(sw++);
               if(sw >= flasherLen){
                    sw = 0;
               }
          }
          //滑入停止动画，滑出开始动画
          _this.hover(function(){
            if(myTime){
               clearInterval(myTime);
            }
          },function(){
            myTime = setInterval(shower, 3000);
          });
          //自动开始
          shower();
          var myTime = setInterval(shower, 3000);
        },
        //-- searchHelp
        searchHelp:function(htmlFunc, clickFunc){
            var pos = $(this).offset();
            var left = pos.left;
            var top = pos.top + $(this).height() + 12;
            var url = $(this).attr('src');
            var func = function(){
                var val = $(this).val();
                var oldVal = $(this).attr('_value');
                $(this).attr('_value', val);
                if('' == val){
                    $('.searchHelp').fadeOut('fast');
                    return true;
                }
                if(oldVal && oldVal == val){
                    $('.searchHelp').fadeIn('fast');
                    return true;
                }
                $.get($.postfix(url + val), function(res){
                    if(res && 0 === res.indexOf('{')){
                        eval('var res = ' + res);
                        if('E00000000' == res.code && 'object' == typeof res.data){
                            var html = htmlFunc(res.data, val);
                            html = '<div class="searchHelp"><div class="closeSearchHelp" title="Close">×</div>' + html + '</div>';
                            $('body').remove('.searchHelp');
                            $('body').append(html);
                            $('.searchHelp').css({position: 'absolute',top:top,left:left});
                            $('.searchHelp .closeSearchHelp').css({position: 'absolute',top:0,right:0, cursor: 'pointer'})
                                                             .click(function(){$('.searchHelp').fadeOut('fast');});
                            $('.searchHelp .row').click(function(){
                                var idx = $('.searchHelp .row').index($(this));
                                clickFunc(res.data[idx]);
                                $('.searchHelp').fadeOut('fast');
                            });
                            return true;
                        }
                    }
                    $('.searchHelp').fadeOut('fast');
                });
            };
            $(this).focus(func);
            $(this).keyup(func);
        },
        //-- tr backgroud color
        trBg: function(evenClass, oddClass, hoverClass){
            $(this).each(function(){
                $(this).find('tr:even').attr('class', evenClass);
                $(this).find('tr:even').hover(function(){$(this).attr('class', hoverClass);}, function(){$(this).attr('class', evenClass);});
                $(this).find('tr:odd').attr('class', oddClass);
                $(this).find('tr:odd').hover(function(){$(this).attr('class', hoverClass);}, function(){$(this).attr('class', oddClass);});
            });
        },
        //-- my map shower
        myMap: function(config){
          var options = {
            mapMark : '#mapMark',
            mapShow : '#mapShow',
            mapDel  : '#mapDel',
            lat     : '#lat',
            lng     : '#lng'
          };
          if(config){
            for(var k in config){
              options[k] = config[k];
            }
          }
          var _this = this;
          var _lat = $(options.lat);
          var _lng = $(options.lng);
          if('function' != typeof window.markMapLatLng){
            window.markMapLatLng = function(_latlng, _type){
              _type = _type || 0;
              if(!_latlng || ',' == _latlng || -1 != _latlng.indexOf('NaN')){
                if(2 == _type){
                  _lat.val('');
                  _lng.val('');
                }
                if(options.mapShow && $(options.mapShow) &&  $(options.mapShow)[0] && 'none' != $(options.mapShow).css('display')){
                    $(options.mapShow + ' iframe').attr('src', 'about:blank');
                    $(options.mapShow).hide();
                }
                return;
              }
              else{
                  $(options.mapDel).val('删除地图');
                  $(options.mapDel).attr('_value','');
              }
              var latlng = _latlng.split(',');
              if(!$(options.mapShow + ' iframe')[0]){
                  $(options.mapShow).html('<iframe src="about:blank" width="500" height="300" frameborder="0" style="border: 1px solid #808080;"></iframe>');
              }
              var url = $(_this).attr('rel')+'?latlng=' + _latlng;
              if(url != $(options.mapShow + ' iframe').attr('src')){
                  _lat.val(latlng[0]);
                  _lng.val(latlng[1]);
                  $(options.mapShow + ' iframe').attr('src', url);
              }
              if($(options.mapShow)[0]){
                  $(options.mapShow).show();
              }
              if(0 == _type && $(options.mapMark)[0]){
                  $(options.mapMark).hide();
              }
            };
          }
          function changeVal(){
            window.markMapLatLng(parseFloat(_lat.val()) + ',' + parseFloat(_lng.val()), 1);
          }
          window.setInterval(changeVal, 1000);
          $(options.mapDel).click(function(){
            if($(this).attr('_value')){
               var latlng = $(this).attr('_value');
               var type = 0;
               $(this).val('删除地图');
               $(this).attr('_value','');
            }
            else{
               var latlng = null;
               var type = 2;
               $(this).val('还原地图');
               $(this).attr('_value', _lat.val() + ',' + _lng.val());
            }
            window.markMapLatLng(latlng, type);
          });
          $(_this).click(function(){
            if(!$(options.mapMark)[0]){
                var id = options.mapMark.substr(1);
                var fix = $.browser.msie&&$.browser.version=='6.0'
                        ? "position:absolute;bottom:auto;top:expression(eval(document.documentElement.scrollTop + 2));"
                        : "position:fixed;bottom:auto;";
                $('body').append('<div style="border: 10px solid #808080;z-index:100000000;top:0px;' + fix + '" id="' + id + '"><div style="top:0px;right:0px;position:absolute;width:15px;height:15px;line-height:15px;text-align:center;font-size:0.8em;cursor:pointer;background:#FFF;border: 5px solid #808080;" class="close" title="Close">×</div><iframe src="about:blank" width="500" height="400" frameborder="0"></iframe></div>');
                $(options.mapMark + ' .close').click(function(){$(options.mapMark).hide();});
                $(options.mapMark).css({'left':($(window).width()-$(options.mapMark).width())/2+'px'});
            }
            var lat = _lat.val();
            var lng = _lng.val();
            var latlng = lat + ',' + lng;
            var url = $(_this).attr('rel')+'?latlng=' + latlng + '&isMark=1';
            if(url != $(options.mapMark + ' iframe').attr('src')){
              $(options.mapMark + ' iframe').attr('src', url);
            }
            $(options.mapMark).show();
          });
        },
        //-- my dialog
        myDialog: function(config){
          options = {
            title : '对话框',
            containment : '',
            show : 'slide',
            hide : 'slide',
            resizable : true,
            width : $(window).width()-50,
            height : $(window).height()-50,
            bgiframe : true,
            modal: false,
            minimized : function(){$(this).dialog('hide');},
            maximized : function(){},
            maximizedOptions : {top:0,left:0,width:0,height:0},
            buttons: {
              '关闭': function() {
                $('#'+dialogId).dialog('close');
              }
            }
          };
          if(config){
              config.tit = config.tit || '';
              for(var i in config){
                  if('undefined' != typeof options[i]){
                    options[i] = config[i];
                  }
              }
          }
          $(this).click(function(){
            options.title = config.tit + $(this).text();
            var url = $(this).attr('href');
            url += (-1 != url.indexOf('?') ? '&' : '?') + '_Layer=1';
            var _this = this;
            $.get(
                $.postfix(url),
                null,
                function(res){
                  var dialogId = 'myDialog';
                  $('#'+dialogId).remove();
                  $('body').append('<div style="width: auto; height: auto;display:none;" id="'+dialogId+'"></div>');
                  $("#dialog").dialog("destroy");
                  var o=$('#'+dialogId);
                  o.html(res);
                  o.dialog(options);
                  o.dialog("moveToTop");
                }
            );
            return false;
          });
        },
        //-- my menu
        myMenu: function(){
            var _this = $(this);
            /* 菜单初始化 */
            _this.find('>ul>li>ul>li:has(ul:not(:empty))>a').append("<span class='arrow'>></span>"); // 为有子菜单的菜单项添加'>'符号
            _this.find('>ul>li').mouseover(function(){ // 顶级菜单项的鼠标移入操作
              $(this).children('ul').slideDown('fast');
            }).mouseleave(function(){ // 顶级菜单项的鼠标移出操作
              $(this).children('ul').slideUp('fast');
            });
            _this.find('>ul>li>ul li').mouseover(function(){ // 子菜单的鼠标移入操作
                $(this).children('ul').slideDown('fast');
            }).mouseleave(function(){// 子菜单的鼠标移出操作
                $(this).children('ul').slideUp('fast');
            });
        },
        //-- my hover style
        myHoverStyle: function(onClass, outClass){
         $(this).mouseover(function(){
            var c = $(this).attr('class');
            if(-1 != c.indexOf(onClass)){
                return false;
            }
            else if(-1 != c.indexOf(outClass)){
               $(this).attr('class', c.replace(outClass, onClass));
            }
            else{
                $(this).attr('class', c + ' ' + onClass);
            }
         })
         .mouseout(function(){
            var c = $(this).attr('class');
            if(-1 != c.indexOf(outClass)){
                return false;
            }
            else if(-1 != c.indexOf(onClass)){
               $(this).attr('class', c.replace(onClass,outClass));
            }
            else{
                $(this).attr('class', c + ' ' + outClass);
            }
         });
       },
       //-- my focus style
       myFocusStyle: function(onClass, outClass){
         $(this).focus(function(){
            var c = $(this).attr('class');
            if(-1 != c.indexOf(onClass)){
                return false;
            }
            else if(-1 != c.indexOf(outClass)){
               $(this).attr('class', c.replace(outClass, onClass));
            }
            else{
                $(this).attr('class', c + ' ' + onClass);
            }
         })
         .blur(function(){
            var c = $(this).attr('class');
            if(-1 != c.indexOf(outClass)){
                return false;
            }
            else if(-1 != c.indexOf(onClass)){
               $(this).attr('class', c.replace(onClass,outClass));
            }
            else{
                $(this).attr('class', c + ' ' + outClass);
            }
         });
       },
       //-- slides
       slides: function(config){
          var _this = this;
          var options = {
            speed : 5000,
            item_width : 207,
            slides_id : '.slides',
            prev_id : '.prev',
            next_id : '.next'
          };
          if(config){
            for(var k in config){
              options[k] = config[k];
            }
          }
          //a simple function to click next link
          //a timer will call this function, and the rotation will begin :)
          function rotate() {
            $(_this).find(options.next_id).click();
          }
          var run = window.setInterval(rotate, options.speed);
          var left_value = options.item_width * (-1);
          //move the last item before first item, just in case user click prev button
          $(_this).find(options.slides_id +' li:first').before($(_this).find(options.slides_id +' li:last'));
          //set the default item to the correct position
          $(_this).find(options.slides_id +' ul').css({'left' : left_value});
          //if user clicked on prev button
          $(_this).find(options.prev_id).click(function() {
              //get the right position
              var left_indent = parseInt($(_this).find(options.slides_id +' ul').css('left')) + options.item_width;
              //slide the item
              $(_this).find(options.slides_id +' ul:not(:animated)').animate({'left' : left_indent}, 200,function(){
                    //move the last item and put it as first item
              $(_this).find(options.slides_id +' li:first').before($(_this).find(options.slides_id +' li:last'));
              //set the default item to correct position
              $(_this).find(options.slides_id +' ul').css({'left' : left_value});
            });
            //cancel the link behavior
            return false;
          });
          //if user clicked on next button
          $(_this).find(options.next_id).click(function() {
              //get the right position
              var left_indent = parseInt($(_this).find(options.slides_id +' ul').css('left')) - options.item_width;
              //slide the item
              $(_this).find(options.slides_id +' ul:not(:animated)').animate({'left' : left_indent}, 200, function () {
              //move the first item and put it as last item
              $(_this).find(options.slides_id +' li:last').after($(_this).find(options.slides_id +' li:first'));
              //set the default item to correct position
              $(_this).find(options.slides_id +' ul').css({'left' : left_value});
            });
            //cancel the link behavior
            return false;
          });
          //if mouse hover, pause the auto rotation, otherwise rotate it
          $(_this).find(options.slides_id).hover(
            function() {
              window.clearInterval(run);
            },
            function() {
              run = window.setInterval(rotate, options.speed);
            });
        }
    });
    //插件
    jQuery.extend({
        //-- msg tip
        msg: function(title, body, showFunc, hideFunc) {
            body = body || '';
            var fix = $.browser.msie&&$.browser.version=='6.0'
                        ? "position:absolute;bottom:auto;top:expression(eval(document.documentElement.scrollTop + 2));"
                        : "position:fixed;bottom:auto;";
            if(!$('.x-msg')[0]){
                var html = ['<div class="x-msg" style="z-index:100000000;top:-100px;' + fix + '">',
                            '<div class="x-box-close" title="Close">×</div>',
                            '<div class="x-box-tl"><div class="x-box-tr"><div class="x-box-tc"></div></div></div>',
                            '<div class="x-box-ml"><div class="x-box-mr"><div class="x-box-mc"></div></div></div>',
                            '<div class="x-box-bl"><div class="x-box-br"><div class="x-box-bc"></div></div></div>',
                            '</div>'].join('');
                $("body").prepend(html);
                $('.x-msg .x-box-close').click(function(){$('.x-msg').hide().css({top: '-100px'});});
            }
            var exp = (hideFunc || (-1 == body.indexOf('<a '))) ? 3000 : 30000;
            $('.x-msg .x-box-mc').html('<h3>'+title+'</h3>'+body);
            $('.x-msg').css({'left':($(window).width()-$('.x-msg').width())/2+'px'});
            $('.x-msg').stop(true, 'hide')
                       .animate({ top: '+0px', opacity: 'show'}, 500, null, showFunc)
                       .delay(exp)
                       .animate({top: '-' + ($('.x-msg').height()+10) + 'px', opacity: 'hide'}, 500, null, hideFunc);
            if($('.x-msg .x-box-mc .sed')[0]){
                window.setInterval(function(){$('.x-msg .x-box-mc .sed').html(parseInt($('.x-msg .x-box-mc .sed').text())-1);},1000);
            }
        },
        //-- api res
        api:function(res, fn, _this){
            if(!_this){
                _this = 'body';
            }
            if(res && 0 === res.indexOf('var res')){
                eval(res);
                switch(res.code){
                    case 'A00006':
                        if('undefined' != typeof fn && null != fn && fn){
                            fn(res.data);
                        }
                        if('undefined' == typeof res.jump){
                            $.msg('信息提示', res.msg);
                        }
                        else if('reload' == res.jump){
                            $.msg('信息提示', res.msg + "<br />　　—— <strong class=\"sed\">3</strong> 秒后，自动<a href=\"javascript:window.location.reload();\">刷新页面</a>。", null, function(){window.location.reload();});
                        }
                        else{
                            $.msg('信息提示', res.msg + "<br />　　—— <strong class=\"sed\">3</strong> 秒后，自动<a href=\"" + res.jump + "\">跳转至新页</a>。", null, function(){window.location = res.jump;});
                        }
                        var cls = $(_this).attr('class');
                        if(cls &&( -1 != cls.indexOf('myDel') || -1 != cls.indexOf('myRemove') || -1 != cls.indexOf('myRecover') )) {
                            $(_this).parent().parent().slideUp(1000);
                        }
                    break;
                    default:
                        $.msg('错误提示', res.msg);
                        if('undefined' != typeof res.data){
                            var id = $(_this).find('[name=' + res.data + ']');
                            if(id[0]){
                                id[0].focus();
                                if('vcode' == res.data){
                                    $('.vcodeChange').click();
                                    id.val('');
                                }
                            }
                        }
                }
              }
              else{
                  $.msg('系统错误', res);
              }
        },
        //-- postfix
        postfix: function(url, b){
            return url += (-1 == url.indexOf('?') ? '?' : '&') +(b ? 'format=json&varname=res&' : '&')  + (new Date()).getTime();
        }
    });
    $.ajaxSetup({
        error:function(x,e){
            if(x.status==0){
                $.msg('系统错误', '(0)You are offline!!\n Please Check Your Network.');
            }else if(x.status==404){
                $.msg('系统错误', '(404)Requested URL not found.');
            }else if(x.status==500){
                $.msg('系统错误', '(500)Internel Server Error.');
            }else if(e=='parsererror'){
                $.msg('系统错误', 'Error.\nParsing JSON Request failed.');
            }else if(e=='timeout'){
                $.msg('系统错误', 'Request Time out.');
            }else {
                $.msg('系统错误', 'Unknow Error.\n'+x.responseText);
            }
        }
    });
    //-- inputStyle config
    if('undefined' == typeof inputStyle){
        inputStyle = ['inputFocus','inputBlur'];
    }
    //-- submitStyle config
    if('undefined' == typeof submitStyle){
        submitStyle = ['submitOver','submitOut'];
    }
    //-- pointer cursor
    $('label,img[rel],.vcodeChange,.mySubmit,input[type=submit],button[type=submit]').css('cursor','pointer');
    //-- Overlay Tip
    $(".OverlayTip[rel^='#']").each(function(){
        if($($(this).attr('rel'))[0])$(this).css('cursor','pointer').overlay({mask: '#000', effect: 'apple', fixed: false});
     });
    //-- Tooltip
    //$("*[title]").tooltip({ position:'bottom center',offset: [-2, 10], effect: "fade", opacity: 0.7 });
    $("*[title]").tooltip({ offset: [10, 2], effect: 'slide'}).dynamic({ bottom: { direction: 'down', bounce: true } });
    //-- VCode
    $('.vcodeChange').live('click',function(){
        $('.vcodeImg').attr("src", $('.vcodeImg').attr('src').replace(/\?(.*)$/ig,'') + '?change=' + new Date().valueOf());
    });
    //-- trBg
    $('thead').next().trBg('','altbg1', 'trMoveOver');
    /*
    $('.editor').rte({
        width: 720,
        height: 300,
        controls_rte: rte_toolbar,
        controls_html: html_toolbar
    });
    */
    //-- Button over style
    $('.mySubmit').myHoverStyle(submitStyle[0], submitStyle[1]);
    //-- Input click style
    $('.myInput').myFocusStyle(inputStyle[0], inputStyle[1]);
    //-- Default value
    $('.myValue[rel]').each(function(){
        var r = $(this).attr('rel');
        if(''==$(this).val()){
            $(this).val(r);
        }
      $(this).focus(function(){
        if($(this).val()==$(this).attr('rel')){
            $(this).val('');
        }
      }).blur(function(){
        if($(this).val()==''){
            $(this).val($(this).attr('rel'));
        }
      });
    });
    $('.mapMark').myMap({
        mapShow : '.mapShow',
        mapDel  : '.mapDel',
        lat     : 'input[name=lat]',
        lng     : 'input[name=lng]'
    });
    //-- Form Post
    $('.myForm').submit(function(){
        return  $(this).myPost();
    });
    //-- Check Post
    $('.myCheck').submit(function(){
        if($(this).required()){
           return false;
        }
        else{
            return true;
        }
    });
    //-- My Get
    $('.myGet').live('click',function(){
        var cls = $(this).attr('class');
        if(-1 != cls.indexOf('myRemove')){
            if(!window.confirm("点击这里将永久删除该信息，无法恢复。\n单击“确定”继续。单击“取消”停止。")){
                return false;
            }
        }
        if(-1 != cls.indexOf('myRecover')){
            if(!window.confirm("点击这里将恢复该信息，恢复后将会显示给用户。\n单击“确定”继续。单击“取消”停止。")){
                return false;
            }
        }
        return  $(this).myGet();
    });
    //-- Menu
    $('.myMenu').myMenu();
    $('.myMenu a').each(function(){
        var url = $(this).attr('href');
        url += (-1 < url.indexOf('?') ? '&':'?' )+ (new Date()).getTime();
        $(this).attr('href',url);
    });
    //-- flasher
    $('.flasher').flasher();
});
