﻿/**
 * jQuery ETSOO Website Plugin 0.1.0
 *
 * Copyright (c) 2011 ETSOO
 *
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 */

/**
	扩展基本对象属性
*/
String.format = function() {
  var s = arguments[0];
  for (var i = 0; i < arguments.length - 1; i++) {       
    var reg = new RegExp("\\{" + i + "\\}", "gm");             
    s = s.replace(reg, arguments[i + 1]);
  }

  return s;
}

String.prototype.endsWith = function (suffix) {
  return (this.substr(this.length - suffix.length) === suffix);
}

String.prototype.startsWith = function(prefix) {
  return (this.substr(0, prefix.length) === prefix);
}

/**
	网站报告类
*/
function ETSOOWebsiteReport(){
	this.data = null;
	this.fullKind = null;
	this.kind = null;
	this.target = null;
	this.showId = null;
	this.fullValue = null;
	this.value = null;
	this.add = null;
}

/**
	解析报告数据

	@param data 报告数据
*/
ETSOOWebsiteReport.prototype.parse = function(data){
	this.data = data;
    if (data != null){
        var element = data.getElementsByTagName("data")[0];
        if (element != null){
            var fullKind = element.getAttribute("name");
            var kParas;
            if(fullKind.indexOf('|') == -1) kParas = fullKind.split('.');
            else kParas = fullKind.split('|');
            this.fullKind = fullKind;
            this.kind = kParas[0];
            this.target = kParas[1];
            this.showId = kParas[2];
            var fullValue = $.trim($(element).text());
            var vParas = fullValue.split('|');
            this.fullValue = fullValue;
            this.value = vParas[0];
            this.add = vParas[1];
        }
    }
}

/**
	获取报告结果的文本

	@returns 文本
*/
ETSOOWebsiteReport.prototype.label = function(){
	var label = $EW.getLanguageText(this.value, true);
	if ( label == '' || label == null) label = "["+this.value+"] "+$EW.getLanguageText("UnknownError");
	var labelAdd = this.add;
	if (labelAdd)
	{
		labelAdd = $EW.getLanguageText(labelAdd);
		label = "[" + labelAdd + "] "+label;
	}
	return label;
}

/**
	获取报告结果指定的对象

	@param form 当前验证的表单或者容器对象

	@returns 报告指定的对象
*/
ETSOOWebsiteReport.prototype.targetElement = function(form){
	var target = this.target;
	var oTarget;
	if (target)
	{
		if (form != null) oTarget = $(form).find('[name="'+target+'"]')[0];
		else oTarget = $('input:text[name="'+target+'"]')[0];
	}
	return oTarget;
}

/**
	网站对象类
*/
function ETSOOWebsite(){
	this.urlParams = this._getUrlParams(); // URL参数
	this.currentLanguage = this._getLanguage(); // 浏览器语言
	this.languageTexts = {}; // 提示文本
	this.onlineData = null; // 在线信息
	this.reportSkin = "default"; // 错误报告皮肤
	
	this.customerLoginDiv = "CustomerLoginDiv"; // 客户登陆容器对象id
};

ETSOOWebsite.language = null; // 默认语言

/**
    刷新验证码的静态方法
 */
ETSOOWebsite.refreshCode = function(image){
	$(image).reload();
}

/**
	判断按键是否为数字

	@param evt HTML元素的onkeypress事件

	@returns 结果，bool
*/
ETSOOWebsite.onlyNumbers = function(evt){
	var e = evt
	if(window.event){ // IE
		var charCode = e.keyCode;
	} else if (e.which) { // Safari 4, Firefox 3.0.4
		var charCode = e.which
	}
	if (charCode == 46 || (charCode > 31 && (charCode < 48 || charCode > 57)))
	    return false;
	return true;
}

/**
	判断按键是否为字母

	@param evt HTML元素的onkeypress事件

	@returns 结果，bool
*/
ETSOOWebsite.onlyLetters = function(evt){
	var e = evt
	if(window.event){ // IE
		var charCode = e.keyCode;
	} else if (e.which) { // Safari 4, Firefox 3.0.4
		var charCode = e.which
	}
	if(charCode <32 || (charCode >=48 && charCode <=57) || (charCode >=65 && charCode <=90) || (charCode >=97 && charCode <=122))
	    return true;
	else
	    return false;
}

/**
    初始化必要参数
 */
ETSOOWebsite.prototype.init = function()
{
	var htmlCode = '<div id="FormLoadingDiv"></div>';
    // 报告代码
    if($("form").length > 0)
    {
		htmlCode += '<div id="'+this.reportSkin+'ErrorReporter"><div class="leftPart">&nbsp;</div><div class="rightPart"> </div></div>';
    }
	$(document.body).append(htmlCode);
}

// 获取浏览器语言
ETSOOWebsite.prototype._getLanguage = function(){
	if(ETSOOWebsite.language) return ETSOOWebsite.language;
	var l = this.urlParams["BL"];
	if(l == null || l == ''){
		l = $.cookie("BL");
		if(l == null || l == ''){
			l =  navigator.language || navigator.userLanguage;
			l = l.toLowerCase();
		}
	}
	return l;
}

// 解析url参数
ETSOOWebsite.prototype._getUrlParams = function(){
	var urlParams = {};
    var e,
        a = /\+/g,
        r = /([^&=]+)=?([^&]*)/g,
        d = function (s) { return decodeURIComponent(s.replace(a, " ")); },
        q = window.location.search.substring(1);

    while (e = r.exec(q))
       urlParams[d(e[1])] = d(e[2]);
	   
	return urlParams;
}

/**
	浏览产品

	@param productID 产品编号

	@returns 无
*/
ETSOOWebsite.prototype.viewProduct = function(productID){
    window.open('/Products/ViewProductWindow.aspx?ProductID='+productID,'ViewProduct','width=660, height=560, titlebar=no, menubar=no, statusbar=no, scrollbars=no');
}

/**
	浏览产品图片

	@param productID 产品编号

	@returns 无
*/
ETSOOWebsite.prototype.viewProductLogo = function(productID){
    window.open('/Products/ViewProductLogo.aspx?ProductID='+productID,'ViewProduct','width=660, height=560, titlebar=no, menubar=no, statusbar=no, scrollbars=no');
}

/**
	浏览产品PDF文档

	@param page PDF文件名

	@returns 无
*/
ETSOOWebsite.prototype.viewPDF = function(page){
	window.open('/ETSOO/EOFile/Root/PDF/'+page+'.pdf');
}

/**
	添加弹出窗口

	@param title 说明文本
	@param removeSeconds 自动移除毫秒数
	@param onUnblock 移除事件处理函数
	@param closable 移除事件处理函数

	@returns 无
*/
ETSOOWebsite.prototype.addPopUp = function(title, removeSeconds, onUnblock, closable){
	if(title == null) title = this.getLanguageText("R_Processing");
	if(removeSeconds == null) removeSeconds = 0;
	if(closable == null) closable = false;
	var jDiv = $("#FormLoadingDiv");
	if(jDiv.length>0)
	{
		var cHtml;
		if(closable) cHtml = '<div class="popUpIcon"><img src="/ETSOO/jquery/etsoo.com/resources/close.gif" /></div>';
		else cHtml = '';
		cHtml += '<div class="popUpTitle">'+title+'</div>';
		jDiv.html(cHtml);
		
        $.blockUI({
            message: jDiv,
			draggable: false,
			timeout: removeSeconds,
			onUnblock: onUnblock
        });
		
		jDiv.find("div.popUpIcon").click(function(){
			$EW.removePopUp({onUnblock: onUnblock});
		});
	}
}

/**
	移除弹出窗口

	@param opts 移除参数

	@returns 无
*/
ETSOOWebsite.prototype.removePopUp = function(opts){
	$.unblockUI(opts);
}

/**
	绑定表单验证

	@param formOrName 表单HTML对象或表单名称
	@param successBeforeAction 成功提交处理前执行的函数
	@param sucessAfterAction 成功提交处理后执行的函数
	@param dataType 返回的数据类型

	@returns 无
*/
ETSOOWebsite.prototype.validateForm = function(formOrName, ops, successBeforeAction, sucessAfterAction, dataType){
	var jForm;
	if(typeof(formOrName) == "string") jForm = $("form[name='"+formOrName+"']");
	else jForm = $(formOrName);
	
	if(jForm.length > 0)
	{
		if(ops == null) ops = {};
	
		if(ops.submitHandler == null){
			ops.submitHandler = function(form){
				$EW.submitForm(form, successBeforeAction, sucessAfterAction, dataType);
			}
		}
		if(ops.showErrors == null){
			ops.showErrors = function(errorMap, errorList){
				$EW.parseValidError(this, errorList, 0);
			}
		}
		
		jForm.validate(ops);
	}
	
	return jForm;
}

/**
	获取验证错误代码

	@param errorList 错误列表
*/
ETSOOWebsite.prototype.parseValidError = function(v, errorList, type){
	var firstError = errorList[0];
	if(firstError == null) return;
	
	var element = firstError.element;
	var message = firstError.message;
	
	var errorMessage = $(element).attr("errorMessage");
	if(errorMessage == null || errorMessage == '') errorMessage = message;
	
	if(type==0)
	{
		this.reportFocus(errorMessage,element);
	}
	else
	{
		v.labelContainer.html(this.getLanguageText(errorMessage));
	}
}

/**
	显示客户登陆窗口，必须提供定位元素element

	@element 定位元素

	@returns 无
*/
ETSOOWebsite.prototype.showCustomerLogin = function(element)
{
    if (element == null) return;
    var jDiv = $("#"+this.customerLoginDiv);
    if (jDiv.length > 0)
    {
        // 设置Cookie
		var customerID = $.cookie("EIISCustomerIDSaved");
        jDiv.find("input:text[name='CustomerID']").attr("value", customerID);
        jDiv.find("input:text[name='VeryCode']").attr("value","");
        jDiv.find("img[onclick='ETSOOWebsite.refreshCode(this)']").click();
		
        var pos = this.calculatePosition(jDiv, element, document.body, 0, 2);
        var left = pos.left;
        var top = pos.top;
        
        $.blockUI({
            message: jDiv,
            css: {
                left: left,
                top: top,
                width: 'auto',
                textAlign: left,
                cursor: 'default'
            },
			onBlock: function()
			{
				if(customerID)
				{
					jDiv.find("input:password[name='Password']").focus();
				}
			}
        });
    }
}

/**
	判断语言是否与当前浏览器匹配

	@param language 判断的语言
	@param restrict 是否严格匹配，默认值为false，如果为true，则en-us和en不是一回事

	@returns 逻辑型
*/
ETSOOWebsite.prototype.testLanguage = function(language, restrict){
	if(restrict == null) restrict = false;
	if(restrict) {
		if(language == this.currentLanguage)return true;
		else return false;
	}
	else{
		if(language == this.currentLanguage || this.currentLanguage.indexOf(language+"-") == 0)return true;
		else return false;
	}
}

/**
	添加翻译文本

	@param items 添加的项目

	@returns 无
*/
ETSOOWebsite.prototype.addLanguageTexts = function(items){
	$.extend(this.languageTexts, items);
}

/**
	获取翻译文本

	@param id 编号
	@param keepBlank 如果找不到，是否返回空

	@returns 翻译文本
*/
ETSOOWebsite.prototype.getLanguageText = function(id, keepBlank){
    if (keepBlank == null) keepBlank = false;
    var label = null;
    if(id.charCodeAt(0) > 160 || id.indexOf(" ") != -1) label = id;
    else label = this.languageTexts[id];
    
    if (label) return label;
    else if(keepBlank) return '';
    else return id;
}

/**
	判断编号是否存在

	@param powerID 权限编号，如 Customer, User, Product
	@param keyValue 编号
	@param resultFunction 结果处理函数，会传递 bool 结果

	@returns 无
*/
ETSOOWebsite.prototype.isKeyAvailable = function(powerID, keyValue, resultFunction){
	$.get("/XmlData/IsKeyAvailable.aspx", {PowerID:powerID, KeyValue:keyValue}, function(data){resultFunction($(data).find("data").text()=="true");});
}

/**
	更新登陆状态

	@param powerID 权限编号，如 Customer, User, Product
	@param keyValue 编号
	@param resultFunction 结果处理函数，会传递 bool 结果

	@returns 无
*/
ETSOOWebsite.prototype.setOnlineUpdate = function(interval){
	// 没有在线信息，读取
	if(this.onlineData==null){
		this.onlineUpdate();
	}
	
	// 循环读取，防止停留时间过长，在线信息失效
	$(document).everyTime(interval, function(){
			$EW.onlineUpdate();
		});
}

/**
	刷新在线信息

	@returns 无
*/
ETSOOWebsite.prototype.onlineUpdate = function(){
	$.get("/XmlData/UpdateOnline.aspx", {id: new Date().valueOf()}, function(data){
				var json = $.xml2json(data);
				if(json.UserID == "undefined")
				{
					json = null;
				}
				$EW.onlineData = json;
				$(document).trigger("onlineUpdate", [json]);
		});
}

/**
	注销登录信息

	@param powerID 权限编号，如 Customer, User, Supplier
	@param clearLogin 是否清除保存的登陆，默认值为false

	@returns 无
*/
ETSOOWebsite.prototype.logout = function(powerID, clearLogin){
    var kind = (clearLogin) ? "Logout" : "";
    $.get("/SmartERP/Tools/Logout.aspx", {PowerID: powerID, Kind: kind}, function(data){$EW.onlineUpdate()});
}

/**
	格式化数字

	@param numbers 要格式化的数字或数字文本

	@returns 带有分隔符的数字文本
*/
ETSOOWebsite.prototype.formatNumber = function(numbers, precision, zeroToEmpty){
	if(precision == null) precision = 2;
	if(zeroToEmpty == null) zeroToEmpty = false;
	if(typeof(numbers) != "number") numbers = parseFloat(numbers);
	if(isNaN(numbers) || numbers==0){
		return zeroToEmpty ? '' : '0';
	}
	
	var nStr = numbers.toFixed(precision);
	var x = nStr.split('.');
	var x1 = x[0];
	var x2 = x.length > 1 ? '.' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + ',' + '$2');
	}
	return x1 + x2;
}

/**
    添加url参数，确保如果存在自动替换
    
    @param url 网址
    @param name 参数名
    @param value 参数值
*/
ETSOOWebsite.prototype.addUrlPara = function(url, name, value){
    var id = name + "=";
    var pos = url.indexOf(id);
    if (pos == -1){
        if (url.indexOf("?") == -1) url += "?";
        else url += "&";
        url += id + value;
    }
    else {
        var endPos = url.indexOf("&", pos+1);
        url = url.substr(0, pos) + id + value;
        if (endPos !=-1) url += url.substr(endPos);
    }
    return url;
}

/**
    计算位置，确保element相对于relativeElement定位，且不超出容器container
    
    @param element 定位的HTML元素
    @param relativeElement 相对定位的元素
    @param container 限制容器
    @param adjustX 调整的水平距离
    @param adjustY 调整的垂直距离
*/
ETSOOWebsite.prototype.calculatePosition = function(element, relativeElement, container, adjustX, adjustY){
    if (adjustX == null) adjustX = 0;
    if (adjustY == null) adjustY = 0;
    
    var jElement = $(element);
    var jRelative = $(relativeElement);
    var jContainer = $(container);

    var maxWidth = jContainer.outerWidth();
    var maxHeight = jContainer.outerHeight();
    
    var w = jElement.outerWidth();
    var h = jElement.outerHeight();
    
    var eW = jRelative.outerWidth();
    var eH = jRelative.outerHeight();
    
    var pos = jRelative.offset();
    
    var left = pos.left + adjustX;
    if ( left + w >  maxWidth) left = left + eW - adjustX - w;
    var top = pos.top + eH + adjustY;
    if ( top + h > maxHeight) top = top - eH - adjustY - h;
    
    return {left: left, top: top};
}

/**
    把处理页面结果的xml数据，解析成Flex风格的report对象
    
    @param data 标准反馈的xml数据
*/
ETSOOWebsite.prototype.parseAsReport = function(data){
    var report = new ETSOOWebsiteReport();
	report.parse(data);
	return report;
}

/**
    报告反馈
    
    @param label 反馈文本
    @param focusElement 焦点HTML元素
*/
ETSOOWebsite.prototype._reportFocus = function(label, focusElement){
    if (focusElement != null){
        var jElement = $(focusElement);
        jElement.focus();
        var pos = jElement.offset();
        var left = pos.left;
        var top = pos.top + jElement.outerHeight();
        var reportID = '#' + this.reportSkin + 'ErrorReporter';
        var jReport = $(reportID);
		
		var clickHandler = function(){
			jReport.hide();
		};
		jReport.unbind("click", clickHandler).bind("click", clickHandler);
		
        jReport.css({left: left, top: top, zIndex: 9999});
        jReport.find(".leftPart").html(label);
        jReport.show();
        
        var fadeOutTimeout = jReport.attr("fadeOutTimeout");
        if (fadeOutTimeout) window.clearTimeout(fadeOutTimeout);
        fadeOutTimeout = window.setTimeout("$('"+reportID+"').fadeOut()",6000);
        jReport.attr("fadeOutTimeout", fadeOutTimeout);
        
		var keyPressHandler = function(){
            jReport.fadeOut();
        };
		
        jElement.unbind("keypress", keyPressHandler).bind("keypress", keyPressHandler);
    }
    else
    {
        alert(label);
    }
}

/**
    解析翻译文本，报告反馈
    
    @param id 翻译编号
    @param element 焦点HTML元素
*/
ETSOOWebsite.prototype.reportFocus = function(id, element)
{
    this._reportFocus(this.getLanguageText(id), element);
}

/**
    把处理页面结果的xml数据，解析成Flex风格的report对象
    
    @param data 标准反馈的xml数据
    @param focusElement 焦点HTML元素
*/
ETSOOWebsite.prototype.report = function(data, focusElement)
{
    if (typeof(data) == "string")
    {
        this._reportFocus(this.getLanguageText(data), focusElement);
    }
    else
    {
        var report;
        if ( data.documentElement != null ) report = this.parseAsReport(data);
        else report = data;
        if (report.kind == "Redirect")
        {
            window.location.href = report.value;
        }
        else
        {
            var label = report.label();
        
            var showId = report.showId;
            if (showId)
            {
                // 指定了现实容器
                $(showId).html(label);
            }
            else
            {
				var oTarget = report.targetElement(focusElement.form);
				if ( oTarget != null ) focusElement = oTarget;
                this._reportFocus(label, focusElement);
            }
        }
    }
}

/**
    提交表单处理，提交路径有action属性指定，提交方法由method属性指定
    
    @param form 表单HTML对象
    @param successBeforeAction 默认处理前执行的函数
    @param successAfterAction 默认处理后执行的函数
    @param dataType 返回数据类型，默认为xml
*/
ETSOOWebsite.prototype.submitForm = function(form, successBeforeAction, successAfterAction, customOPs){
    var ops = { dataType: "xml"};
	if(customOPs != null ) $.extend(ops, customOPs);
	var dataType = ops.dataType;
    var jForm = $(form);
    var url =  ops.action;
	if(url == null || url == '') url = jForm.attr("action");
    var formType = jForm.attr("method");
    if(formType == null || formType == '')formType = "GET";
    else formType = formType.toUpperCase();
    var formData = jForm.serialize();
    var submitButton;
	var isBlocking = $.isBlocking();
    var jSubmitButtons = jForm.find(":submit");
    if (jSubmitButtons.length > 0) submitButton = jSubmitButtons[0];
    $.ajax({
        type: formType,
        url: url,
        dataType: dataType,
        cache: false,
        data: formData,
        beforeSend: function()
        {
			if(isBlocking){
				jSubmitButtons.attr("disabled",true);
			}
			else{
				$EW.addPopUp();
			}
        },
        error: function(jqXHR, textStatus)
        {
			var errorMessage = "Ajax: "+textStatus;
			if(isBlocking){
				$EW.report(errorMessage, submitButton);
			}
			else{
				$EW.addPopUp(errorMessage, 6000);
			}
        },
        success: function(data)
        {
			if(isBlocking){
				jSubmitButtons.attr("disabled",false);
			}
			else{
				$EW.removePopUp({fadeOut:0});
			}
			
            var report = $EW.parseAsReport(data);
            
            if (successBeforeAction != null && successBeforeAction(form, report, submitButton) === false) return;
            
            if(report.kind == "Redirect")
            {
                var backUrl = form.elements["BackUrl"];
                if (backUrl)
                {
                    window.location.href = backUrl;
                }
            }
            else
            {
				$EW.reportForm(form, report, submitButton);
            }

            if (successAfterAction != null)
            {
                successAfterAction(form, report, submitButton);
            }
        }
    });
    return false;
}

/**
    报告提交表单结果
    
    @param form 表单HTML对象
*/
ETSOOWebsite.prototype.reportForm = function(form, report, submitButton){
	this.report(report, submitButton);
	
	if (report.value == "R_NoVeryCode"){
		var oCode;
		if(report.target) oCode = form.elements[report.target];
		else {
			oCode = $(form).find("input[errorMessage='R_NoVeryCode']")[0];
			oCode.focus();
		}
		if( oCode != null ){
			oCode.value = "";
		}
	}
	$(form).find("img[onclick='ETSOOWebsite.refreshCode(this)']").click();
}

/**
    验证外部配置表单
    
    @param form 表单HTML对象
*/
ETSOOWebsite.prototype.submitKVForm = function(form, url)
{
    var valid = true;
    var elements = form.elements.length;
    for(var i=0; i<elements; i++)
    {
        var e = form.elements[i];
        var required = e.getAttribute("required");
        if(required == "true")
        {
            var hasValue = false;
            var nodeName = e.nodeName;
            var type = e.type;
            if(nodeName == "INPUT")
            {
                if(type == "text" || type == "url" || type == "email" || type == "phone")
				{
                    if(e.value != "")
                    {
                        hasValue = true;
                    }
                }
                else if(type == "radio" || type == "checkbox")
                {
                    var items = form.elements[e.name];
                    var len = items.length;
                    for(var h = 0; h < len; h++)
                    {
                        var item = items[h];
                        if(item.checked)
                        {
                            hasValue = true;
                            break;
                        }
                    }
                }
                else hasValue=true;
            }
            else if(nodeName == "SELECT")
            {
                if(e.selectedIndex > 0)
                {
                    hasValue = true;
                }
            }
            else if(nodeName == "TEXTAREA")
            {
                if(e.value != "")
                {
                    hasValue = true;
                }
            }
            else hasValue = true;
            
            if(!hasValue)
            {
                valid = false;
                var jE = $(e);
                jE.focus();
                var borderColor = jE.borderColor();
                jE.css("borderColor","#ff0000");
                jE.unbind("change");
                jE.bind("change", function(){
                    $(this).css("borderColor", borderColor);
                });
                break;
            }
        }
    }
    
    if (valid)
    {
        valid = $EW.submitForm(form, function(form, report, submitButton){
            var reportValue = report.value;
            if (reportValue.indexOf("KVFileSent") != -1)
            {
				$EW.addPopUp($EW.getLanguageText(reportValue), 6000, function(){
					window.location.href="/";
					}, true);
				return false;
            }
        });
    }
    
    return valid;
}

/**
	实现滚动效果

	@param oContainer 容器HTML对象，需要定义明确的宽度和高度
	@param selfOptions 请参考options定义说明

	@returns 无
*/
ETSOOWebsite.prototype.marquee = function(oContainer, selfOptions){
	var container = $(oContainer);
	if( container.length == 0 || container.children().length == 0 ){
		return;
	}
	
	// 读取容器宽度和高度
	var width = parseInt(container.css("width"));
	var height = parseInt(container.css("height"));
	if( isNaN(width) || isNaN(height) ){
		return;
	}
	
	// 设置默认属性
	container.css("overflow", "hidden");
	
	// 动画层对象，默认清除缩进
	var layer = $(container.children()[0]);
	if( layer.children().length == 0) return;
	layer.css("padding", 0);
	layer.css("margin", 0);
	layer.children().css("float","left");

	// 默认参数
	var options = {
		/**
		 * pushleft - 显示一行，每次左移一图
		 * pushright - 显示一行，每次右移一图
		 * pushup - 显示一列，每次上移一图
		 * pushdown - 显示一列，每次下移一图
		 * fadeinout - 同时淡入淡出替换
		 */
		slideType: "pushleft",
		// 对应 JQuery 的 duration，为三种预定速度之一的字符串("slow", "normal", or "fast")或表示动画时长的毫秒数值(如：1000)
		duration: "slow",
		// 两次切换效果之间停留时间
		stayTime: 4000,
		// 多个元素之间默认的marginRight
		defaultMargin: 8
	};
	
	// 设置自定义参数
	if( typeof(selfOptions) == "object" ) $.extend(options,selfOptions);
	
	// 类型
	var type = options.slideType;
	
	// 是否初始化
	var loaded = false;
	
	switch (type){
		case "pushleft":
		case "pushright":
			// 如果没有设置margin，设置默认的margin
			var marginRight = parseInt(layer.children().css("marginRight"));
			if ( isNaN(marginRight) || marginRight == 0 )
			{
				marginRight = options.defaultMargin;
				layer.children().css("marginRight", marginRight);
			}
			
			layer.css("width", (2 * width)); // 留出右侧足够空间

			if( type == "pushright") 
			{
				var firstNode = $(layer.children()[0]);
				layer.css("marginLeft", -(firstNode.width() + marginRight)); //留出左侧一个元素空间
			}
			
			$.everyTime( options.stayTime, function(){
				var firstNode = $(layer.children()[0]);
				if( type == "pushleft")
				{
					firstNode.animate(
						{marginLeft: -(firstNode.width() + marginRight)},
						options.duration,
						function(){
							firstNode.appendTo(layer);
							firstNode.css("marginLeft",0);
						}
					);
				}
				else
				{
					firstNode.animate(
						{marginLeft: firstNode.width() + marginRight},
						options.duration,
						function(){
							$(layer.children(":last")).insertBefore(firstNode);
							firstNode.css("marginLeft",0);
						}
					);
				}
			});
			break;
		case "pushup":
		case "pushdown":
			// 如果没有设置margin，设置默认的margin
			var marginBottom = parseInt(layer.children().css("marginBottom"));
			if ( isNaN(marginBottom) || marginBottom == 0 )
			{
				marginBottom = options.defaultMargin;
				layer.children().css("marginBottom", marginBottom);
			}
			
			// 水平浮动
			layer.css("height", (2 * height));
			if( type == "pushdown") 
			{
				var firstNode = $(layer.children()[0]);
				layer.css("marginTop", -(firstNode.height() + marginBottom)); //留出上端一个元素空间
			}
			
			$.everyTime( options.stayTime, function(){
				var firstNode = $(layer.children()[0]);
				if( type == "pushup")
				{
					firstNode.animate(
						{marginTop: -(firstNode.height() + marginBottom)},
						options.duration,
						function(){
							firstNode.appendTo(layer);
							firstNode.css("marginTop",0);
						}
					);
				}
				else
				{
					firstNode.animate(
						{marginTop: firstNode.height() + marginBottom},
						options.duration,
						function(){
							$(layer.children(":last")).insertBefore(firstNode);
							firstNode.css("marginTop",0);
						}
					);
				}
			});
			break;
		case "fadeinout":
			// 效果索引
			var currentIndex = 0;
			
			// 子元素数量
			var count = layer.children().length;
			
			// 最大索引
			var maxIndex = 0;
			
			// 每次显示的数量
			var countTime = 0;
			
			// 第一个元素
			var firstNode = $(layer.children()[0]);
			
			// 缩进
			var marginRight = parseInt(firstNode.css("marginRight"));
			if( isNaN(marginRight) ) marginRight = 0;
			var marginBottom = parseInt(firstNode.css("marginBottom"));
			if( isNaN(marginBottom) ) marginBottom = 0;
			
			// 智能判断
			if (width > height && marginRight == 0)
			{
				marginRight = options.defaultMargin;
				layer.children().css("marginRight", marginRight);
				
			}
			else if( marginBottom == 0)
			{
				marginBottom = options.defaultMargin;
				layer.children().css("marginBottom", marginBottom);
			}

			// Duration
			var duration = options.duration;
			
			$.everyTime(options.stayTime, function(){
				if ( ! loaded) // 确保元素已经完整加载
				{
					// 计算可见对象
					var itemWidth = firstNode.width() + marginRight;
					var itemHeight = firstNode.height() + marginBottom;
					var countW = Math.round(width / itemWidth);
					var countH = Math.round(height / itemHeight);
					countTime = countW * countH;
					
					// 最大索引
					maxIndex = Math.ceil(count / countTime) - 1;
					if( maxIndex < 1 ) return;
					
					// 除当前可见的元素隐藏
					layer.children().slice(countTime, count).hide();
					
					// 设置绝对定位
					layer.css("position","relative");
					layer.children().css("position","absolute");
					
					// 设置元素位置，叠加排列在第一排
					for(var c = 0; c < count; c ++)
					{
						var child = $(layer.children()[c]);
						var x = c % countW;
						child.css("left", x * itemWidth);
						child.css("top",0);
					}
				
					loaded = true;
				}
				
				var items = layer.children().slice(currentIndex * countTime, (currentIndex + 1) * countTime);
				items.fadeOut(duration);
				currentIndex ++;
				if(currentIndex > maxIndex ) currentIndex = 0;
				var visibleItems = layer.children().slice(currentIndex * countTime, (currentIndex + 1) * countTime);
				visibleItems.fadeIn(duration);
			});
			
			break;
	}
}

// 网站对象
var $EW = new ETSOOWebsite();

// 扩展jQuery
(function($) {
	
$.extend($.fn, {
	// 获取边框颜色
    borderColor: function(){
        var borderColor = this.css("borderColor");
        var runtimeStyle = this.context.runtimeStyle;
        if (runtimeStyle != null && runtimeStyle.borderColor != borderColor) borderColor = '';
        return borderColor;
    },
	// 设置格式化的数字列表
	setNumber: function(numbers, precision, zeroToEmpty){
		this.text($EW.formatNumber(numbers, precision, zeroToEmpty));
	},
	// 重新加载图片
	reload: function(){
		this.each(
			function(i){
				var jImage = $(this);
				var src = jImage.attr("src");
				var autoid = Math.round( 100000 * Math.random()).toString() + Math.round( 100000 * Math.random()).toString();
				src = $EW.addUrlPara(src, "_autoid", autoid);
				jImage.attr("src", src);
			});
	},
	// 设置滚动效果
	marquee: function(selfOptions){
		this.each(
			function(i){
				$EW.marquee(this, selfOptions);
			});
	}
});

})(jQuery);
