﻿/**
 * 创建代理函数
 * @param {Object} obj 函数作用域
 * @param {Object} args 函数传递参数
 * @param {Object} appendArgs 是否追加参数
 */
Function.prototype.createDelegate = function(obj, args, appendArgs){
    var method = this;
	
    return function() {
        var callArgs = args || arguments;
		
        if(appendArgs === true){
            callArgs = Array.prototype.slice.call(arguments, 0);
            callArgs = callArgs.concat(args);
        }else if(typeof appendArgs == "number"){
            callArgs = Array.prototype.slice.call(arguments, 0); // copy arguments first
            var applyArgs = [appendArgs, 0].concat(args); // create method call params
            Array.prototype.splice.apply(callArgs, applyArgs); // splice them in
        };
		
        return method.apply(obj || window, callArgs);
    };
};

var EWS = {};//定义命名空间:EWS

/**
 * 返回计算中英文字符的长度
 * @param {String} str
 * @return {Number}
 */
EWS.LenB = function(str){
	return str.replace(/[^\x00-\xff]/g,"**").length;
};

/**
 * 返回字符串的内容，从指定位置开始拿取指定长度内容，长度按字符数计算
 * @param {String} str 指定字符串
 * @param {Number} start 指定起始位置
 * @param {Number} len 指定字符数
 * @return {String}
 */
EWS.MidB = function(str , start , len){
	var newstr = '';

	if(str == undefined){
		return newstr;
	};
	
	if(start == undefined){
		return str;
	};
	
	if(len == undefined){
		len = EWS.LenB(str);
	};
	
	var total = str.length;//字符串总个数
	var end = 0;//终点位置
	var currAmount = 0;//当前个数
	var regular = /[^\x00-\xff]/;
		
	for(var i=0; i<total; i++){
		currAmount++;
		var temp = str.substring(i,i+1);

		if(regular.test(temp)){
			end+=2;
		}else{
			end++;
		};
		
		if(end>=len){
			break;
		};
	};
	
	return str.substring(0,currAmount);
};

/**
 * 根据提供的字符串与对象，使用规则匹配后生成并返回
 * 规则一：{str}，将str替换为指定的变量
 * @param {Object} str
 * @param {Object} lang
 * @return {String}
 */
EWS.applyTemplate = function(str , obj){
	var arr = str.match(/\{(\w*)\}/g);
	
	if(arr != null){
		for(var i=0,len=arr.length; i<len; i++){
			var t = arr[i].replace("{", "");
			t = t.replace("}", "");
			str = str.replace(arr[i], obj[t]);
		};
		
		return str;
	}else{
		return str;
	};
};

/**
 * 对象克隆
 * @param {Object} myObj
 */
EWS.clone = function (myObj){
	  if(typeof(myObj) != 'object'){
	  	return myObj;
	  };
	  
	  if(myObj == null){
	  	return myObj;
	  }; 
	  
	  if(myObj.length != undefined ){
	  	var myNewObj = new Array();
	  }else{
	  	var myNewObj = new Object();
	  };
	  
	  for (var i in myObj) {
	  	myNewObj[i] = clone(myObj[i]);
	  };
	  
	  return myNewObj;
};

/**
 * 当模板Logo为png24时，IE6的解决方法
 */
function LogoPng24Fix(){
    if ($.browser.msie) {
        var version = $.browser.version;
        if (version == 6.0) {
			//当IMG是空的时候，执行返回
            var img = $('#logo img');
            if (img.length == 0) {
                return;
            }
            var imgTarget = img[0];
            var ImgObj = new Image();
            ImgObj.src = imgTarget.src;
            var fun = function(ImgObj){
            //正则表达式：当src里面包含png的时候，以下操作
	            if (imgTarget.src.match(/\.png$/i) != null) {
	            	var url = window.location.href;
	            	if(url.match(/\.local/i) != null){
	            		url = 'http://www1.khews.local/theme/global/style/img/apalt.gif';
	            	}else{
	            		url = 'http://www1.khews.com/theme/global/style/img/apalt.gif';
	            	}
	                imgTarget.style.cssText = 'width:' + ImgObj.width + 'px;height:' + ImgObj.height + 'px;background:none;filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src="' + imgTarget.src + '",sizingMethod="crop");';
	                imgTarget.src = url;
	            }
            };
            if (ImgObj.readyState == "complete") {
                fun(ImgObj);
            }
            ImgObj.onreadystatechange = function(){
                if (this.readyState == "complete") {
                    fun(ImgObj);
                }
            };
        }
    }
};

/**
 * 设置图片背景（当图片为png gif背景透明时，删除背景图片即去除class）
 */
function removeBackImage(){

	function set(obj){
		var len = obj.length;
		if(len == 0) return;
		var appname = navigator.appName.toLowerCase();
		if (appname.indexOf("netscape") == -1){//IE
			for(var i=0;i<len;i++){
				if (obj[i].readyState == "complete"){
					obj[i].className = '';
				}else{
	               obj[i].onreadystatechange =function(){
	               	  if (this.readyState == "complete"){
		               	  this.className = '';
		               	  this.onreadystatechange = function(){};
	               	  }
	               }
				}
			}
		}else{//FF
			for(var i=0;i<len;i++){
				if (obj[i].complete == true){
					obj[i].className = '';
				}else{
	               obj[i].onload =function(){
	               	  if (this.complete == true){
		               	  this.className = '';
		               	  this.onload = function(){};
	               	  }
	               }
				}
			}
		}
	};	
	set($('img[class="noimage"][src$=".gif"]'));
	set($('img[class="noimage"][src$=".png"]'));
};

/**
 * 重新设置页面
 */
EWS.resetLayout = function(){
	//设置head(因head是否有内容进行显示/隐藏)
	var header = $('#header');
	var pagebottom = $('#pagebottom');
	if($.trim(header.html()) == ''){
		header.hide();
	}else{
		var top = header.find('#top');
		var nav = header.find('#nav');
		var logo = header.find('#logo');
		var banner = header.find('#banner');
		if(!top[0]&&!nav[0]&&!banner[0]&&!logo[0]){
			header.hide();
		}else{
			if(top[0]&&$.trim(top.html()) == ''){
				header.hide();
			}
		} 
	}
	
	var navbar = $('#navbar');
	if(navbar[0]&&$.trim(navbar.html())==''){
		navbar.hide();
	}
	
	if($.trim(pagebottom.html()) == ''){
		pagebottom.hide();
	}
	
	//旧版本情况下没有这个变量,或者不是全屏时不用设置
	if(!EWS.setLayout||EWS.setLayout.full == '1') return;
	var len = EWS.setLayout.layout.length;
	//首先要判断页面的版式
	var width = '';//页面宽度
	var fullScreen = document.body.offsetWidth;
	if(EWS.setLayout.pageType == 2){//首页版式
		width = fullScreen;
		var ediContainer = $('#ediContainer');
		var wrapper = $('#wrapper');
	}else{//内容页版式
		width = fullScreen-EWS.setLayout.pageScale;
		$('#mainContent')[0].style.width = width+'px';
		$('#ediContainer')[0].style.width = width+'px';
	}
	for(var i=0;i<len;i++){
		setFull(EWS.setLayout.layout[i]);
//		if(Number(EWS.setLayout.layout[i].type) == 0){//全屏
//			setFull(EWS.setLayout.layout[i]);
//		}else{//像素
//			setPixel(EWS.setLayout.layout[i]);
//		}
	}
	
	//一行一列
	var oneLine = $('.layout_wrap1');
	var oneLineLen = oneLine.length;
	for(var k=0;k<oneLineLen;k++){
		$(oneLine[k]).find('div')[0].style.width = width+'px';
	}
	
	function setFull(data){//全屏设置
		var parent = $('#'+data.objId);
		var point = data.point.split(',');
		var div = $('#'+data.objId+'>div');
		if(data.cls == '2'){//一行两列
			var realWidth = width - Number(data.margin);
			var left = realWidth*Number(point[0])/100;
			var right = realWidth*Number(point[1])/100;
			div[0].style.width = left+'px';
			div[2].style.width = right+'px';
			parent[0].style.width = width+'px';
		}else{//一行三列
			var realWidth = width - 2*Number(data.margin);
			var left = realWidth*Number(point[0])/100;
			var middle = realWidth*Number(point[1])/100;
			var right = realWidth*Number(point[2])/100;
			div[0].style.width = left+'px';
			div[2].style.width = middle+'px';
			div[4].style.width = right+'px';
			parent[0].style.width = width+'px';
		}
		
	};
//	function setPixel(data){//像素设置
//		var parent = $('#'+data.objId);
//		var point = data.point.split(',');
//		var div = $('#'+data.objId+'>div');
//		if(data.cls == '2'){//一行两列
//			var realWidth = width - Number(data.margin);
//			var left = realWidth*Number(point[0])/100;
//			var right = realWidth*Number(point[1])/100;
//			div[0].style.width = left+'px';
//			div[2].style.width = right+'px';
//			parent[0].style.width = width+'px';
//		}else{
//			var realWidth = width - 2*Number(data.margin);
//			var left = realWidth*Number(point[0])/100;
//			var middle = realWidth*Number(point[1])/100;
//			var right = realWidth*Number(point[2])/100;
//			div[0].style.width = left+'px';
//			div[2].style.width = middle+'px';
//			div[4].style.width = right+'px';
//			parent[0].style.width = width+'px';
//		}
//	};
};


//设置导航栏选中页面
var setNavClass = function(){
//	var url = window.location.href.split('/');
//	var urlName = url[url.length-1];
//	
//	//当前页面
//	alert($('#menuContent li>a[href="'+urlName+'"]').html());
//	
//	//第几套模板
//	alert($('link[href$="global.css"]').attr('href').indexOf('theme_029'))
	if($('link[href$="global.css"]').attr('href').indexOf('theme_029')){
		var state = window.location.href.split('/');
		var len = state.length;
		var stateUrlArr = state[len-1].split('?')
		var stateUrl =  stateUrlArr[0];
		var li = $('#menuContent li>a[href="'+stateUrl+'"]').parent();
		if(li){
			li.addClass('status').attr('key',1);
			EWS.navSpe = true;
		}
		
	}
	
};


$(document).ready(function(){
	LogoPng24Fix();
	EWS.resetLayout();
	removeBackImage();
	setNavClass();
});
/***********************************菜单导航*****************************************************/
var menuIndex = 0;

/**
 * 菜单移动
 * @param {Number} way 0：向左移，1:向右移
 * @param {Object} menuCount 菜单总数量
 * @param {Number} n 显示个数
 */
function menuTurn(way, menuCount, n){
	if (menuCount <= n){ 
	    return;
	};
	
	if (way == 0) {
	/*前移*/
	    var index = menuIndex - 1;
	}else if (way == 1) {
	/*后移*/
	    var index = menuIndex + 1;
	};
    
    /*做移动操作的条件*/
    if (menuCount - index >= n && index >= 0) {
        menuIndex = index;
		var dis , cls;
		 
        /*循环一级菜单，控制隐藏和显示项*/
        for (var i = 0; i < menuCount; i++) {
            if (i >= menuIndex && i < (menuIndex + n)) {
                dis = '';
            } else {
                dis = 'none';
            };
            
            //当前最后一个菜单使用last样式
            if(i == (menuIndex + n - 1)){
            	cls = 'last';
            }else{
            	cls = '';
            };
			
            //设置一级菜单
            var menu_lv1 = document.getElementById('ewsmenuList_' + i);
            menu_lv1.style.display = dis;
            menu_lv1.className = cls;
            
            /*循环二级菜单，控制下级菜单显示的方向*/
            for (var j = 0; 1 == 1; j++) {
                var menu_lv2 = document.getElementById('ewsmenuList_' + i + '_' + j);
                
                /*停止遍历所有二级菜单*/
                if (!menu_lv2){
                    break;
                };
                    
                
                //判断二级菜单是否有下级菜单
                if( menu_lv2.getElementsByTagName('ul').length ){
                	/*判断是否最后二项，如果是，则反转下级菜单显示方向,二级菜单第一个加first样式,最后一个加last样式*/
	                if ((i + 2 - menuIndex) >= n ) {
	                	menu_lv2.className = j == 0?'left first':(!document.getElementById('ewsmenuList_' + i + '_' + (j+1))?'left last':'left');
	                }else {
	                	menu_lv2.className = j == 0?'right first':(!document.getElementById('ewsmenuList_' + i + '_' + (j+1))?'right last':'right');
	                };
	                menu_lv2.getElementsByTagName('li')[0].className = 'first';
                }else{
                	menu_lv2.className = j == 0?'first':(!document.getElementById('ewsmenuList_' + i + '_' + (j+1))?'last':'');
                };                
            };
            
        };
    };
};

/***********************************侧栏：二级菜单*****************************************************/
function sideMenuLoad(id, selectId){
	 var str='';
	 var position='<p>当前位置 : 首页 >> ';
	 
     for(var i=0; i<sideMenuData.length; i++){
	       if(sideMenuData[i].ID == id){
		   
		          str = "<h3 id='sideMenu_1'>"+sideMenuData[i].label+"</h3><div class='rank_a'><ul id='sideMenu_2'>";

				  position += sideMenuData[i].label;
				  
				  var menu2 = sideMenuData[i].children;
				  var str2='';
				  var position2='';
				  var menu2_len  = menu2.length;
				  
				  for(var j=0; j<menu2_len; j++){
				         var menu3=menu2[j].children;
						 
						 if(menu2[j].ID==selectId){ position2 = ' >> '+ menu2[j].label; };
						  
						 if(menu3.length>0){
						     
							 if(menu2[j].ID==selectId){ dis=''; }else{dis='none';};
							 
							 //设置当前层样式
							 var menu_cls = 'alt';
							 if(j == 0){
							 	var menu_cls = 'first alt';//设置当前层首个菜单样式
							 };
							 if(j == menu2_len - 1){
							 	var menu_cls = 'last alt';//设置当前层最后一个菜单样式
							 };
							 
							 if(menu2[j].IsLink == 0){
							 	 var href = menu2[j].ID+'.shtml';
							 }else{
								 var href = menu2[j].LinkPath;
							 };
							 
						      str2 += "<li class='"+menu_cls+"'><a href='"+href+"'>"+menu2[j].label+"</a>";
							
						     /****************处理第三层菜单************************开始**********/
							 var str3='';
							 var menu3_len = menu3.length;
							 for(var k=0; k<menu3_len; k++){
							 
							    if(menu3[k].ID==selectId){
								    dis='';
									position2 = ' >> '+ menu2[j].label + ' >> '+ menu3[k].label;
								};
								
								 var menu_cls = '';
							 	 if(k == 0){
								 	var menu_cls = 'first';//设置当前层首个菜单样式
								 };
								 if(k == menu3_len - 1){
								 	var menu_cls = 'last';//设置当前层最后一个菜单样式
								 };
								 
								 if(menu3[k].IsLink == 0){
									 var href = menu3[k].ID+'.shtml';
								 }else{
									 var href = menu3[k].LinkPath;
								 };
								
							    str3 += "<li class='"+menu_cls+"'><a href='"+href+"'>"+menu3[k].label+"</a></li>";
							 };
							  /****************处理第三层菜单**********************************/
							 
							 str2 += '<a class="status" href="javascript:void(0);" onclick="sideMenuExpand('+ "'" + 'menu2_' + j + "'" +')" ></a><div id="menu2_' + j +'" class="rank_b" style="display:'+dis+'"><ul>';
							 str2 = str2 + str3 + "</ul></div></li>";
							 
						 }else{
						 	 var menu_cls = '';
							 
						 	 if(j == 0){
							 	var menu_cls = 'first';//设置当前层首个菜单样式
							 };
							 if(j == menu2_len - 1){
							 	var menu_cls = 'last';//设置当前层最后一个菜单样式
							 };
							 
							 if(menu2[j].IsLink == 0){
							 	 var href = menu2[j].ID+'.shtml';
							 }else{
								 var href = menu2[j].LinkPath;
							 };
							 
			                 str2 += "<li class='"+menu_cls+"'><a href='"+href+"'>"+menu2[j].label+"</a></li>"; 
						 };
				  };
				  
				  str = str + str2 + "</ul></div>";
				  break;
		   };
	 };
	 
	 position = position + position2 + '</p>';
	 
	 if(document.getElementById('position')){
	 	document.getElementById('position').innerHTML=position;
	 };
	 
	 return str;
};

function sideMenuExpand(clickId){
     var sideMenu_2=document.getElementById('sideMenu_2');
	 var disDiv=sideMenu_2.getElementsByTagName('div');
	 for(var i=0; i<disDiv.length; i++){
	      disDiv[i].style.display='none';
	 };
	 document.getElementById(clickId).style.display='';
};

/***********************************侧栏：滚动广告*****************************************************/

function slidePlayer_load(width,height){

	var imgs=document.getElementById('slidePlayer').getElementsByTagName('img');
	var divs=document.getElementById('slidePlayer').getElementsByTagName('div');
	
	for(var i=0; i<imgs.length; i++){
	  
			var w=imgs[i].width;
			var h=imgs[i].height;
			
			var wMatch=width-w;
			var hMatch=height-h;
			if( wMatch<0 || hMatch<0 ){
				if(wMatch < hMatch){ 
					imgs[i].width=width; 
					imgs[i].height=h*width/w; 
				}else{
					imgs[i].height=height;
					imgs[i].width=w*height/h;
				}
			}
			
			divs[i].style.width=width+'px';
			divs[i].style.height=height+'px';
	}
	
	var marquee1 = new Marquee('slidePlayer'); 
	marquee1.Direction = 'top';
	marquee1.Step = 10;
	marquee1.Width = width;
	marquee1.Height = height;
	marquee1.Timer = 50;
	marquee1.DelayTime = 5000;
	marquee1.WaitTime = 3000;
	marquee1.ScrollStep = height;
	marquee1.Start();
	
}

function Marquee()
{
	this.ID = document.getElementById(arguments[0]);
	if(!this.ID)
	{
		alert("您要设置的\"" + arguments[0] + "\"初始化错误\r\n请检查标签ID设置是否正确!");
		this.ID = -1;
		return;
	};
	this.Direction = this.Width = this.Height = this.DelayTime = this.WaitTime = this.Correct = this.CTL = this.StartID = this.Stop = this.MouseOver = 0;
	this.Step = 1;
	this.Timer = 30;
	this.DirectionArray = {"top":0 , "bottom":1 , "left":2 , "right":3};
	if(typeof arguments[1] == "number" || typeof arguments[1] == "string")this.Direction = arguments[1];
	if(typeof arguments[2] == "number")this.Step = arguments[2];
	if(typeof arguments[3] == "number")this.Width = arguments[3];
	if(typeof arguments[4] == "number")this.Height = arguments[4];
	if(typeof arguments[5] == "number")this.Timer = arguments[5];
	if(typeof arguments[6] == "number")this.DelayTime = arguments[6];
	if(typeof arguments[7] == "number")this.WaitTime = arguments[7];
	if(typeof arguments[8] == "number")this.ScrollStep = arguments[8];
	this.ID.style.overflow = this.ID.style.overflowX = this.ID.style.overflowY = "hidden";
	this.ID.noWrap = true;
	this.IsNotOpera = (navigator.userAgent.toLowerCase().indexOf("opera") == -1);
	if(arguments.length >= 7)this.Start();
};


Marquee.prototype.Start = function()
{
	if(this.ID == -1)return;
	if(this.WaitTime < 800)this.WaitTime = 800;
	if(this.Timer < 20)this.Timer = 20;
	if(this.Width == 0)this.Width = parseInt(this.ID.style.width);
	if(this.Height == 0)this.Height = parseInt(this.ID.style.height);
	if(typeof this.Direction == "string")this.Direction = this.DirectionArray[this.Direction.toString().toLowerCase()];
	this.HalfWidth = Math.round(this.Width / 2);
	this.HalfHeight = Math.round(this.Height / 2);
	this.BakStep = this.Step;
	this.ID.style.width = this.Width + "px";
	this.ID.style.height = this.Height + "px";
	if(typeof this.ScrollStep != "number")this.ScrollStep = this.Direction > 1 ? this.Width : this.Height;
	var msobj = this;
	var timer = this.Timer;
	var delaytime = this.DelayTime;
	var waittime = this.WaitTime;
	msobj.StartID = function(){msobj.Scroll()};
	msobj.Continue = function()
				{
					if(msobj.MouseOver == 1)
					{
						setTimeout(msobj.Continue,delaytime);
					}
					else
					{	clearInterval(msobj.TimerID);
						msobj.CTL = msobj.Stop = 0;
						msobj.TimerID = setInterval(msobj.StartID,timer);
					}
				};

	msobj.Pause = function()
			{
				msobj.Stop = 1;
				clearInterval(msobj.TimerID);
				setTimeout(msobj.Continue,delaytime);
			};

	msobj.Begin = function()
		{
			msobj.ClientScroll = msobj.Direction > 1 ? msobj.ID.scrollWidth : msobj.ID.scrollHeight;
			if((msobj.Direction <= 1 && msobj.ClientScroll <= msobj.Height + msobj.Step) || (msobj.Direction > 1 && msobj.ClientScroll <= msobj.Width + msobj.Step))return;
			msobj.ID.innerHTML += msobj.ID.innerHTML;
			msobj.TimerID = setInterval(msobj.StartID,timer);
			if(msobj.ScrollStep < 0)return;
			msobj.ID.onmousemove = function(event)
						{
							if(msobj.ScrollStep == 0 && msobj.Direction > 1)
							{
								var event = event || window.event;
								if(window.event)
								{
									if(msobj.IsNotOpera)
									{
										msobj.EventLeft = event.srcElement.id == msobj.ID.id ? event.offsetX - msobj.ID.scrollLeft : event.srcElement.offsetLeft - msobj.ID.scrollLeft + event.offsetX;
									}
									else
									{
										msobj.ScrollStep = null;
										return;
									}
								}
								else
								{
									msobj.EventLeft = event.layerX - msobj.ID.scrollLeft;
								}
								msobj.Direction = msobj.EventLeft > msobj.HalfWidth ? 3 : 2;
								msobj.AbsCenter = Math.abs(msobj.HalfWidth - msobj.EventLeft);
								msobj.Step = Math.round(msobj.AbsCenter * (msobj.BakStep*2) / msobj.HalfWidth);
							}
						};
			msobj.ID.onmouseover = function()
						{
							if(msobj.ScrollStep == 0)return;
							msobj.MouseOver = 1;
							clearInterval(msobj.TimerID);
						};
			msobj.ID.onmouseout = function()
						{
							if(msobj.ScrollStep == 0)
							{
								if(msobj.Step == 0)msobj.Step = 1;
								return;
							}
							msobj.MouseOver = 0;
							if(msobj.Stop == 0)
							{
								clearInterval(msobj.TimerID);
								msobj.TimerID = setInterval(msobj.StartID,timer);
							}
						};
		};
	setTimeout(msobj.Begin,waittime);
};

Marquee.prototype.Scroll = function()
{
	switch(this.Direction)
	{
		case 0:
			this.CTL += this.Step;
			if(this.CTL >= this.ScrollStep && this.DelayTime > 0)
			{
				this.ID.scrollTop += this.ScrollStep + this.Step - this.CTL;
				this.Pause();
				return;
			}
			else
			{
				if(this.ID.scrollTop >= this.ClientScroll)
				{
					this.ID.scrollTop -= this.ClientScroll;
				}
				this.ID.scrollTop += this.Step;
			}
		break;

		case 1:
			this.CTL += this.Step;
			if(this.CTL >= this.ScrollStep && this.DelayTime > 0)
			{
				this.ID.scrollTop -= this.ScrollStep + this.Step - this.CTL;
				this.Pause();
				return;
			}
			else
			{
				if(this.ID.scrollTop <= 0)
				{
					this.ID.scrollTop += this.ClientScroll;
				}
				this.ID.scrollTop -= this.Step;
			}
		break;

		case 2:
			this.CTL += this.Step;
			if(this.CTL >= this.ScrollStep && this.DelayTime > 0)
			{
				this.ID.scrollLeft += this.ScrollStep + this.Step - this.CTL;
				this.Pause();
				return;
			}
			else
			{
				if(this.ID.scrollLeft >= this.ClientScroll)
				{
					this.ID.scrollLeft -= this.ClientScroll;
				}
				this.ID.scrollLeft += this.Step;
			}
		break;

		case 3:
			this.CTL += this.Step;
			if(this.CTL >= this.ScrollStep && this.DelayTime > 0)
			{
				this.ID.scrollLeft -= this.ScrollStep + this.Step - this.CTL;
				this.Pause();
				return;
			}
			else
			{
				if(this.ID.scrollLeft <= 0)
				{
					this.ID.scrollLeft += this.ClientScroll;
				}
				this.ID.scrollLeft -= this.Step;
			}
		break;
	}
};

/***********************************引导页滚动图片*****************************************************/
function PicAD_CLS(){	
	var _this = this;
	this.main = function(){
		this.PicList = document.getElementById('IndexPicList');
		this.PicListEls = this.PicList.getElementsByTagName('img');
		this.index = 0;
		
		this.intervalFN();
		
		this.timeID = setInterval(function(){
			_this.intervalFN();
		},2500);
	};
	
	this.intervalFN = function(){
		for(var index = 0; index < this.PicListEls.length; index++) {
			if(this.index % this.PicListEls.length == index){
				this.PicListEls[index].style.display = "";
			}else{
				this.PicListEls[index].style.display = "none";
			};
		};
		this.index++;
	};
};


/***********************************更新网站菜单*****************************************************/
//function UpdateWebMenu(){
//	var loca = window.location.toString();
//	var pattern = /^http:\/\/(\w*\.*\w*\.*\w*\.*\w*)\//;
//	var len = loca.lastIndexOf("/");
//	var lk = loca.substring(0,len).replace('http://','');
//	var MenuA = document.getElementsByName('ewsmenu_link');
//	var MenuA_len = MenuA.length;
//	
//	for(var i=0; i<MenuA_len; i++){
//		if(MenuA[i].href.indexOf('ewsscene.cfm') != -1){
//			MenuA[i].href +='&lk='+lk;
//			break;
//		};
//	};
//	
//	//菜单当前状态样式设定
//	var menu = document.getElementById('menuContent');
//	var menu_li = menu.getElementsByTagName('LI');
//	var li_len = menu_li.length;
//	var timeId;
//	
//	for(var i=0; i<li_len; i++){
//		menu_li[i].onmouseover = function(){
//		   // clearTimeout(timeId);
//
//			//判断当前是第一级
//		    if( this.parentNode.id == "menuContent"){
//		    	this.className = 'status';
//		    };
//		    
//			//判断当前是第二级
////		    if( this.parentNode.parentNode.nodeName == 'LI' ){
////		    	this.parentNode.parentNode.className = 'status';
////		    };
////		    
////		    //判断当前是第三级
////		    if( this.parentNode.parentNode.parentNode.parentNode.nodeName == 'LI' ){
////		    	this.parentNode.parentNode.parentNode.parentNode.className = 'status';
////		    };
//		};
//		
//		menu_li[i].onmouseout= function(){
//			var _this = this;
//			
//			timeId = setTimeout(function(){
//				//判断当前是第一级
//			    if( _this.parentNode.id == "menuContent"){
//			    	_this.className = '';
//			    };
//			    
////				//判断当前是第二级
////			    if( _this.parentNode.parentNode.nodeName == 'LI' ){
////			    	_this.parentNode.parentNode.className = '';
////			    };
////			    
////			    //判断当前是第三级
////			    if( _this.parentNode.parentNode.parentNode.parentNode.nodeName == 'LI' ){
////			    	_this.parentNode.parentNode.parentNode.parentNode.className = '';
////			    };
//			},500);
//		};
//	};
//	
//};
function UpdateWebMenu(){
	var loca = window.location.toString();
	var pattern = /^http:\/\/(\w*\.*\w*\.*\w*\.*\w*)\//;
	var len = loca.lastIndexOf("/");
	var lk = loca.substring(0,len).replace('http://','');
	var MenuA = document.getElementsByName('ewsmenu_link');
	var MenuA_len = MenuA.length;
	
	//替换菜单路径
	for(var i=0; i<MenuA_len; i++){
		if(MenuA[i].href.indexOf('ewsscene.cfm') > -1){
			MenuA[i].href +='&lk='+lk;
			break;
		};
	};
	
	//菜单当前状态样式设定
	var menuLink = document.getElementsByName('ewsmenu_link');
	var menu_len = menuLink.length;
	var li = document.getElementById('menuContent').childNodes;
	var li_len = li.length;
	var timeID;
	
	for(var i=0; i < menu_len; i++){
		menuLink[i].onmouseover = function(){
			if(!EWS.navSpe) clearTimeout(timeID);
			for(var x=0; x < li_len; x++){
				if(li[x].className != ""){
					if(li[x].className.indexOf('last')>-1){
						
					}else if(li[x].className.indexOf('status')>-1){
						
					}else{
						li[x].className = "";
					}
//					if(li[x].className.indexOf('last')==-1){
//						li[x].className = "";
//					}else{
//						li[x].className = "last";
//					}
				};
			};
			
			if(this.parentNode.id){
				var idArr = this.parentNode.id.split("_");
			}else{
				var id = this.parentNode.parentNode.parentNode.id;
				
				//兼容IE6
				if(id==""){
					id = this.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.id;		
				};
				
				var idArr = id.split("_");
			};
			
			if(idArr.length>=3){
				idArr.splice(2,1);
			};
			var newID = idArr.join("_");
			var tli = document.getElementById(newID);
			var thisC = tli.className;
//            if(thisC.indexOf('last')!=-1){
//				document.getElementById(newID).className = 'last status';
//            }else{
//            	document.getElementById(newID).className = 'status';
//            }
            
		};
		
		menuLink[i].onmouseout = function(){
			var _this = this;
			timeID = setTimeout(function(){
				if(_this.parentNode.id){
					var idArr = _this.parentNode.id.split("_");
				}else{
					var id = _this.parentNode.parentNode.parentNode.id;
				
					//兼容IE6
					if(id==""){
						id = _this.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.id;		
					};
					
					var idArr = id.split("_");
				};
				if(idArr.length>=3){
					idArr.splice(2,1);
				};
				var newID = idArr.join("_");
				var tli = document.getElementById(newID);
				if($(tli).attr('key')!=1)
//					tli.className = tli.className.replace('status','');
					$(tli).removeClass('status');
			},1);
		};
	};
};


/**
 * 根据地址栏参数获得指定值
 * @param {String} name 参数名称
 */
//function getParam(name){
//	var winParam = window.location.href.split("?");
//	
//	if (winParam.length > 1) {
//		var urlParam = winParam[1].split('&');
//		var urlLength = urlParam.length;
//		
//		for (var i = 0; i < urlLength; i++) {
//			if (urlParam[i].indexOf(name+"=")>-1) {
//				return urlParam[i].split("=")[1];
//			};
//		};
//	};
//	
//	return '';
//};
function getParam(name, url) {

    var winParam = (url || window.location.href).toString().split("?");

    if (winParam.length > 1) {
        var urlParam = winParam[1].split('&');
        var urlLength = urlParam.length;

        for (var i = 0; i < urlLength; i++) {
            if (urlParam[i].toUpperCase().indexOf(name.toUpperCase() + "=") > -1) {
                return urlParam[i].split("=")[1].replace('#', '');
            };
        };
    };

    return '';
};

/**
 * 预加载图片,预加载完成后替换指定ID的图片
 * .path {String} 统一指定每张图片的加载路径
 * .arrSrc {Object} src:图片文件路径 id:图片id
 * .callBack {Object} 全部加载完成后回调函数 返回 arrsrc数组
 * .maxWidth {Number} 指定每张图片的最大宽度
 * .maxHeight {Number} 指定每张图片的最大高度
 * @param {Object} arg
 */
EWS.PreLoadImage =  function(arg){
    var IE = $.browser.msie;
	var Opera = $.browser.opera;
	var FF = $.browser.mozilla || $.browser.safari;
	this.ImgPath = arg.path == undefined ? "" : arg.path;//图片路径
	this.Length = arg.arrSrc.length;//需要处理图片数量
    this.LoadedLen = 0;//已经被加载的图片个数
    var self = this;
    
	//若图片队列为空则调用回调函数
	if(self.Length<1){
        if(arg.callBack){
			if(arg.scope != undefined){
				arg.callBack.call(arg.scope,arg.arrSrc);
			}else{
				arg.callBack(arg.arrSrc);
			};
		};
        return;
    };
    
    //经测试,OPERA与别的浏览器加载方式不同,所以特别独立开来...
    if(Opera){
        for(var i=0;i<self.Length;i++){
            var tmpImg = new Image();
            tmpImg.src = this.ImgPath+arg.arrSrc[i];
			
            tmpImg.onload = function(){
                self.ProcessImg(this.id,this.width,this.height);
                self.LoadedLen++;
                
                //处理每次加载完成
                if(arg.success){
					if(arg.scope != undefined){
						arg.success.call(arg.scope,arg.arrSrc);
					}else{
						arg.success(arg.arrSrc);
					};
				};
				
				//处理所有加载完成
                if(self.LoadedLen==self.Length && arg.complete){
					if(arg.scope != undefined){
						arg.complete.call(arg.scope,arg.arrSrc);
					}else{
						arg.complete(arg.arrSrc);
					};
				};
            };
			
            //图片加载处理
			tmpImg.onerror = function(){
                self.LoadedLen++;
                
                //处理每次加载完成
                if(arg.error){
					if(arg.scope != undefined){
						arg.error.call(arg.scope,arg.arrSrc);
					}else{
						arg.error(arg.arrSrc);
					};
				};
				
				//处理所有加载完成
                if(self.LoadedLen==self.Length && arg.complete){
					if(arg.scope != undefined){
						arg.complete.call(arg.scope,arg.arrSrc);
					}else{
						arg.complete(arg.arrSrc);
					};
				};
			};
        };
		
        return;
    };
    
    /**
     * 计算出比例值，若含有小数点则取出小数点两位
     * @param {Number} num1 原始值
     * @param {Number} num2　参考值
     * @return {Number}
     */
    this.CalculateScale = function(num1 , num2){
    	var Temp = num2 / num1;
		
		if(Temp.length > 1){
			return num2;
		}else{
			return parseFloat(Temp.toString().substring(0,4));
		};
    };
    
    /**
     * 图片处理函数 
     * @param {Number} w 图片原始宽度
     * @param {Number} h 图片原始高度
     */
    this.ProcessImg = function(id,w,h){    	
    	var img = document.getElementById(id);
    	if(img==undefined){return;};

		img.src = self.ImgPath+arg.arrSrc[self.LoadedLen].src;
		
		//清空noimage样式
		if(img.className == "noimage"){
			img.className = "";
		};
		if(arg.maxWidth == undefined && arg.maxHeight == undefined){
			img.width = w;
			img.height = h;
		}else{
			
			if(w>0 && h>0){   
			    if(w/h>= arg.maxWidth/arg.maxHeight){   
			        if(w>arg.maxWidth){   
			        	newWidth = arg.maxWidth;
			        	newHeight = (h*arg.maxWidth)/w;
			        }else{   
			        	newWidth = w;
			        	newHeight = h;
			        }   
			     }else{   
			        if(h>arg.maxHeight){  
			        	newWidth = (w*arg.maxHeight)/h;
			        	newHeight = arg.maxHeight;
			        }else{   
			        	newWidth = w;
			        	newHeight = h;
			        }   
			    }   
	    	} 
			
			img.width = newWidth;
			img.height = newHeight;
		};
    };
    
    
    /**
     * 加载完毕处理函数
     * @param {object} img
     */
    this.Loaded=function(img){
		self.LoadedLen++;
        
		//处理每次加载完成
		if(arg.success){
			if(arg.scope != undefined){
				arg.success.call(arg.scope,img);
			}else{
				arg.success(img);
			};
		};
		
        if(self.LoadedLen<self.Length){
			self.DownImg();
		}else{
			//处理所有加载完成
			if(arg.complete){
				if(arg.scope != undefined){
					arg.complete.call(arg.scope,arg.arrSrc);
				}else{
					arg.complete(arg.arrSrc);
				};
			};
		};
    };
    
    /**
     * 加载出错处理函数
     * @param {object} img
     */
    this.LoadError=function(img){
		self.LoadedLen++;
        
		//处理每次加载完成
		if(arg.error){
			if(arg.scope != undefined){
				arg.error.call(arg.scope,img);
			}else{
				arg.error(img);
			};
		};
		
        if(self.LoadedLen<self.Length){
			self.DownImg();
		}else{
			//处理所有加载完成
			if(arg.complete){
				if(arg.scope != undefined){
					arg.complete.call(arg.scope,arg.arrSrc);
				}else{
					arg.complete(arg.arrSrc);
				};
			};
		};
    };
    
    /**
     * 加载图片
     */
    this.DownImg=function(){
        var tmpImg = new Image();
		tmpImg.id = arg.arrSrc[self.LoadedLen].id;
        tmpImg.src = self.ImgPath+arg.arrSrc[self.LoadedLen].src;
		
        var options = {id:tmpImg.id,src:tmpImg.src,index:self.LoadedLen};
        
        if(IE){            
            if(tmpImg.readyState=="complete"){
            	options.width = tmpImg.width;
            	options.height = tmpImg.height;
            	self.ProcessImg(tmpImg.id,tmpImg.width,tmpImg.height);
            	self.Loaded(options);
			}else{
				tmpImg.onreadystatechange=function(){
					if(this.readyState=="complete"){
						options.width = this.width;
            			options.height = this.height;            			
						self.ProcessImg(this.id,this.width,this.height);
						self.Loaded(options);
					};
				};
			};
        }else{
			tmpImg.onload = function(){
				options.width = this.width;
            	options.height = this.height;
				self.ProcessImg(this.id,this.width,this.height);
				self.Loaded(options);
			};
		};
		
		//图片加载处理
		tmpImg.onerror = function(){
			self.LoadError(options);
		};
    };
	
    this.DownImg();
};

/**
 * 跳转页面获取分类id及对应组件序号
 */
EWS.getCataLog = function(){
	var val = getParam('catName');
	if(val){
		val = val.split(',');
	};
	return val;
};

/**
 * 类别：公用基类
 * 功能：对地址锚点进行处理（增、删、改）
 */
EWS.Anchor = function(){
	var _getLocation = function(){
		return window.location.href;
	};
	
	var _getAnchor = function(){
		var loc = _getLocation();
		var pos = loc.indexOf("#");
		
		//处理：没有锚点标记
		if(pos==-1){
			return null;
		};
		
		var anchor = loc.substring(pos+1);
		
		//处理：锚点标记后的值为空
		if(anchor.length == 0){
			return null;
		};
		
		return anchor.split("&");
	};
	
	return {
		/**
		 * 写入锚点值，若已经存在则覆盖原有值
		 * @param {String} name
		 * @param {String} value
		 * @return {Boolean} 若锚点已经存在则return true,否则return false
		 */
		set : function(name,value){
			if(name == ""){
				return false;
			};
			
			var arrAnchor = _getAnchor();
			var loc = _getLocation();
			var pos = loc.indexOf("#");
			var href = loc.substring(0,pos);
			
			//没有锚点或者锚点为空处理
			if(arrAnchor == null){
				window.location = href + "#" + name+"="+value;
				return false;
			};
			
			var result = false;
			
			//遍历查找与name匹配的值，并返回
			$.each(arrAnchor , function(i,v){
				if(v.indexOf(name+"=")>-1){
					result = true;
					arrAnchor[i] = name+"="+value;
					return false;
				};
			});
			
			if(result==false){
				arrAnchor.push(name+"="+value);
			};
			
			window.location = href + "#" + arrAnchor.join("&");
		
			return result;
		},
		
		
		/**
		 * 获得与name匹配的值，并返回
		 *  @param {String} name
		 *  @return {String} 若锚点已经存在则return string,否则return null
		 */
		get : function(name){
			var arrAnchor = _getAnchor();
			
			//没有锚点或者锚点为空处理
			if(arrAnchor == null){
				return null;
			};
			
			var result = null;
			
			//遍历查找与name匹配的值，并返回
			$.each(arrAnchor , function(i,v){
				if(v.indexOf(name+"=")>-1){
					result = v.split("=")[1];
					return false;
				};
			});
		
			return result;
		},
		
		/**
		 * 写入锚点值，若已经存在则覆盖原有值
		 * @param {String} name
		 * @return {Boolean} 若锚点已经存在则return true,不存在则return false
		 */
		remove : function(name){
			if(name == ""){
				return false;
			};
			
			var arrAnchor = _getAnchor();
			
			//没有锚点或者锚点为空处理
			if(arrAnchor == null){
				return false;
			};
			
			var result = false;
			
			//遍历查找与name匹配的值，并返回
			var newArr = $.grep(arrAnchor , function(n,i){
				if(n.indexOf(name+"=")>-1){
					result = true;
					return false;
				}else{
					return true;
				};
			});
			
			if(result){
				var loc = _getLocation();
				var pos = loc.indexOf("#");
				var href = loc.substring(0,pos);
				window.location = href + "#" + newArr.join("&");
			};
		
			return result;
		}
	};
}();

/**
 * 获得页面大小和窗口大小
 * @return {Object}
 */
EWS.GetPageSize = function(){
  var scrW, scrH;
  
  if(window.innerHeight && window.scrollMaxY) {
    // Mozilla
    scrW = window.innerWidth + window.scrollMaxX;
    scrH = window.innerHeight + window.scrollMaxY;
  } else if(document.body.scrollHeight > document.body.offsetHeight){
    // all but IE Mac
    scrW = document.body.scrollWidth;
    scrH = document.body.scrollHeight;
  } else if(document.body) { // IE Mac
    scrW = document.body.offsetWidth;
    scrH = document.body.offsetHeight;
  };
  
  var winW, winH;
  
  if(window.innerHeight) { // all except IE
    winW = window.innerWidth;
    winH = window.innerHeight;
  } else if (document.documentElement 
    && document.documentElement.clientHeight) {
    // IE 6 Strict Mode
    winW = document.documentElement.clientWidth; 
    winH = document.documentElement.clientHeight;
  } else if (document.body) { // other
    winW = document.body.clientWidth;
    winH = document.body.clientHeight;
  };
  
  // for small pages with total size less then the viewport
  var pageW = (scrW<winW) ? winW : scrW;
  var pageH = (scrH<winH) ? winH : scrH;
  
  return {PageW:pageW, PageH:pageH, WinW:winW, WinH:winH};
};


/**
 * 给出滚动条的位置
 * @return {Object}
 */
EWS.GetPageScroll = function() {
  var x, y;
  
  if(window.pageYOffset) {
    // all except IE
    y = window.pageYOffset;
    x = window.pageXOffset;
  } else if(document.documentElement 
    && document.documentElement.scrollTop) {
    // IE 6 Strict
    y = document.documentElement.scrollTop;
    x = document.documentElement.scrollLeft;
  } else if(document.body) {
    // all other IE
    y = document.body.scrollTop;
    x = document.body.scrollLeft; 
  };
  
  return {X:x, Y:y};
};

//专为页面加载立体场景使用，由网站监测引擎调用
//function EWS_Monitor_Scene(guestName){
//	var FlashWidth = document.documentElement.clientWidth;
//	var FlashHeight = document.documentElement.clientHeight;
//	guestNickName = guestName;
//
//	var flashvars = {};
//	
//	var attr = {name:'EWS_Scene_CS'};
//	
//	var params = {};
//	params.id='EWS_Scene_CS';
//	params.name='EWS_Scene_CS';
//	params.menu = "false";
//	params.quality = "autohigh";
//	params.wmode = "opaque";
//	params.bgcolor = '#000000';
//	params.flashvars="cfg=http://www.khwws.com/ews_scene_widget/&sceneID="+ EWS_Monitor_Arg.cid +"&charStyle=1&NickName="+guestName+"&chat=false&bgAlpha=0";
//	params.allowscriptaccess="always";
//	
//	swfobject.embedSWF('http://www.khwws.com/ews_scene_widget/CS_widget.swf',
//			'EWS_Scene_CS', FlashWidth, FlashHeight, '9.0.0',
//			"http://www.khwws.com/ews_scene_widget/expressInstall.swf",  flashvars, params );
//};

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
 * Create a cookie with the given name and value and other optional parameters.
 *
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Set the value of a cookie.
 * @example $.cookie('the_cookie', 'the_value', { expires: 7, path: '/', domain: 'jquery.com', secure: true });
 * @desc Create a cookie with all available options.
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Create a session cookie.
 * @example $.cookie('the_cookie', null);
 * @desc Delete a cookie by passing null as value. Keep in mind that you have to use the same path and domain
 *       used when the cookie was set.
 *
 * @param String name The name of the cookie.
 * @param String value The value of the cookie.
 * @param Object options An object literal containing key/value pairs to provide optional cookie attributes.
 * @option Number|Date expires Either an integer specifying the expiration date from now on in days or a Date object.
 *                             If a negative value is specified (e.g. a date in the past), the cookie will be deleted.
 *                             If set to null or omitted, the cookie will be a session cookie and will not be retained
 *                             when the the browser exits.
 * @option String path The value of the path atribute of the cookie (default: path of page that created the cookie).
 * @option String domain The value of the domain attribute of the cookie (default: domain of page that created the cookie).
 * @option Boolean secure If true, the secure attribute of the cookie will be set and the cookie transmission will
 *                        require a secure protocol (like HTTPS).
 * @type undefined
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */

/**
 * Get the value of a cookie with the given name.
 *
 * @example $.cookie('the_cookie');
 * @desc Get the value of a cookie.
 *
 * @param String name The name of the cookie.
 * @return The value of the cookie.
 * @type String
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */
jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        };
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            };
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        };
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                };
            };
        };
        return cookieValue;
    };
};

////////////////////////////////////////////////////////////////////////////////////////////////////////////////

/*
 * jQuery JSON Plugin
 * version: 1.0 (2008-04-17)
 *
 * This document is licensed as free software under the terms of the
 * MIT License: http://www.opensource.org/licenses/mit-license.php
 *
 * Brantley Harris technically wrote this plugin, but it is based somewhat
 * on the JSON.org website's http://www.json.org/json2.js, which proclaims:
 * "NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.", a sentiment that
 * I uphold.  I really just cleaned it up.
 *
 * It is also based heavily on MochiKit's serializeJSON, which is 
 * copywrited 2005 by Bob Ippolito.
 */
 
(function($) {   
    function toIntegersAtLease(n) 
    // Format integers to have at least two digits.
    {    
        return n < 10 ? '0' + n : n;
    }

    Date.prototype.toJSON = function(date)
    // Yes, it polutes the Date namespace, but we'll allow it here, as
    // it's damned usefull.
    {
        return this.getUTCFullYear()   + '-' +
             toIntegersAtLease(this.getUTCMonth()) + '-' +
             toIntegersAtLease(this.getUTCDate());
    };

    var escapeable = /["\\\x00-\x1f\x7f-\x9f]/g;
    var meta = {    // table of character substitutions
            '\b': '\\b',
            '\t': '\\t',
            '\n': '\\n',
            '\f': '\\f',
            '\r': '\\r',
            '"' : '\\"',
            '\\': '\\\\'
        };
        
    $.quoteString = function(string)
    // Places quotes around a string, inteligently.
    // If the string contains no control characters, no quote characters, and no
    // backslash characters, then we can safely slap some quotes around it.
    // Otherwise we must also replace the offending characters with safe escape
    // sequences.
    {
        if (escapeable.test(string))
        {
            return '"' + string.replace(escapeable, function (a) 
            {
                var c = meta[a];
                if (typeof c === 'string') {
                    return c;
                }
                c = a.charCodeAt();
                return '\\u00' + Math.floor(c / 16).toString(16) + (c % 16).toString(16);
            }) + '"';
        }
        return '"' + string + '"';
    };
    
    $.toJSON = function(o, compact)
    {
        var type = typeof(o);
        
        if (type == "undefined")
            return "undefined";
        else if (type == "number" || type == "boolean")
            return o + "";
        else if (o === null)
            return "null";
        
        // Is it a string?
        if (type == "string") 
        {
            return $.quoteString(o);
        }
        
        // Does it have a .toJSON function?
        if (type == "object" && typeof o.toJSON == "function") 
            return o.toJSON(compact);
        
        // Is it an array?
        if (type != "function" && typeof(o.length) == "number") 
        {
            var ret = [];
            for (var i = 0; i < o.length; i++) {
                ret.push( $.toJSON(o[i], compact) );
            }
            if (compact)
                return "[" + ret.join(",") + "]";
            else
                return "[" + ret.join(", ") + "]";
        }
        
        // If it's a function, we have to warn somebody!
        if (type == "function") {
            throw new TypeError("Unable to convert object of type 'function' to json.");
        }
        
        // It's probably an object, then.
        var ret = [];
        for (var k in o) {
            var name;
            type = typeof(k);
            
            if (type == "number")
                name = '"' + k + '"';
            else if (type == "string")
                name = $.quoteString(k);
            else
                continue;  //skip non-string or number keys
            
            var val = $.toJSON(o[k], compact);
            if (typeof(val) != "string") {
                // skip non-serializable values
                continue;
            }
            
            if (compact)
                ret.push(name + ":" + val);
            else
                ret.push(name + ": " + val);
        }
        return "{" + ret.join(", ") + "}";
    };
    
    $.compactJSON = function(o)
    {
        return $.toJSON(o, true);
    };
    
    $.evalJSON = function(src)
    // Evals JSON that we know to be safe.
    {
        return eval("(" + src + ")");
    };
    
    $.secureEvalJSON = function(src)
    // Evals JSON in a way that is *more* secure.
    {
        var filtered = src;
        filtered = filtered.replace(/\\["\\\/bfnrtu]/g, '@');
        filtered = filtered.replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']');
        filtered = filtered.replace(/(?:^|:|,)(?:\s*\[)+/g, '');
        
        if (/^[\],:{}\s]*$/.test(filtered))
            return eval("(" + src + ")");
        else
            throw new SyntaxError("Error parsing JSON, source is not valid.");
    };
})(jQuery);

String.prototype.Trim = function() { return this.replace(/(^\s*)|(\s*$)/g, ""); } 
	
