﻿var FrontRowTimeLeft = 0;

jQuery.fn.extend({
	everyTime: function(interval, label, fn, times, belay) {
		return this.each(function() {
			jQuery.timer.add(this, interval, label, fn, times, belay);
		});
	},
	oneTime: function(interval, label, fn) {
		return this.each(function() {
			jQuery.timer.add(this, interval, label, fn, 1);
		});
	},
	stopTime: function(label, fn) {
		return this.each(function() {
			jQuery.timer.remove(this, label, fn);
		});
	}
});

jQuery.event.special

jQuery.extend({
	timer: {
		global: [],
		guid: 1,
		dataKey: "jQuery.timer",
		regex: /^([0-9]+(?:\.[0-9]*)?)\s*(.*s)?$/,
		powers: {
			// Yeah this is major overkill...
			'ms': 1,
			'cs': 10,
			'ds': 100,
			's': 1000,
			'das': 10000,
			'hs': 100000,
			'ks': 1000000
		},
		timeParse: function(value) {
			if (value == undefined || value == null)
				return null;
			var result = this.regex.exec(jQuery.trim(value.toString()));
			if (result[2]) {
				var num = parseFloat(result[1]);
				var mult = this.powers[result[2]] || 1;
				return num * mult;
			} else {
				return value;
			}
		},
		add: function(element, interval, label, fn, times, belay) {
			var counter = 0;
			
			if (jQuery.isFunction(label)) {
				if (!times) 
					times = fn;
				fn = label;
				label = interval;
			}
			
			interval = jQuery.timer.timeParse(interval);

			if (typeof interval != 'number' || isNaN(interval) || interval <= 0)
				return;

			if (times && times.constructor != Number) {
				belay = !!times;
				times = 0;
			}
			
			times = times || 0;
			belay = belay || false;
			
			var timers = jQuery.data(element, this.dataKey) || jQuery.data(element, this.dataKey, {});
			
			if (!timers[label])
				timers[label] = {};
			
			fn.timerID = fn.timerID || this.guid++;
			
			var handler = function() {
				if (belay && this.inProgress) 
					return;
				this.inProgress = true;
				if ((++counter > times && times !== 0) || fn.call(element, counter) === false)
					jQuery.timer.remove(element, label, fn);
				this.inProgress = false;
			};
			
			handler.timerID = fn.timerID;
			
			if (!timers[label][fn.timerID])
				timers[label][fn.timerID] = window.setInterval(handler,interval);
			
			this.global.push( element );
			
		},
		remove: function(element, label, fn) {
			var timers = jQuery.data(element, this.dataKey), ret;
			
			if ( timers ) {
				
				if (!label) {
					for ( label in timers )
						this.remove(element, label, fn);
				} else if ( timers[label] ) {
					if ( fn ) {
						if ( fn.timerID ) {
							window.clearInterval(timers[label][fn.timerID]);
							delete timers[label][fn.timerID];
						}
					} else {
						for ( var fn in timers[label] ) {
							window.clearInterval(timers[label][fn]);
							delete timers[label][fn];
						}
					}
					
					for ( ret in timers[label] ) break;
					if ( !ret ) {
						ret = null;
						delete timers[label];
					}
				}
				
				for ( ret in timers ) break;
				if ( !ret ) 
					jQuery.removeData(element, this.dataKey);
			}
		}
	}
});

jQuery(window).bind("unload", function() {
	jQuery.each(jQuery.timer.global, function(index, item) {
		jQuery.timer.remove(item);
	});
});

function validateEmail(obj)
{
    var str=obj.val();
    str=quanjiao2Banjiao(str);
    var patn=/^[_a-zA-Z0-9\-]+(\.[_a-zA-Z0-9\-]*)*@[a-zA-Z0-9\-]+([\.][a-zA-Z0-9\-]+)+$/;
    if(patn.test(str))
    {
        return 0;
    }
    else
    {
        return 1;
    }
}

function quanjiao2Banjiao(str)
{
    var i;
    var result='';
    for(i=0;i<str.length;i++)
    {
        code=str.charCodeAt(i);
        if(code>=65281&&code<65373)
        {
            result+=String.fromCharCode(str.charCodeAt(i)-65248);
        }
        else
        {
            result+=str.charAt(i);
        }
    }
    return result;
}

function GetObjects()
{
	var ajax=false;
	/*@cc_on @*/
	/*@if (@_jscript_version >= 5)
	try 
	{ 
		ajax = new ActiveXObject("Msxml2.XMLHTTP"); 
	}
	catch (e)
	{ 
 		try
 		{ 
			ajax = new ActiveXObject("Microsoft.XMLHTTP"); 
		}
		catch (E)
		{ 
			try
			{
				ajax = new XMLHttpRequest(); 
			}
			catch(e)
			{
				ajax = false;
			}
		} 
	}
	@end @*/
	
	if (!ajax && typeof XMLHttpRequest!='undefined') { 
		ajax = new XMLHttpRequest(); 
	}
	return ajax;
}

//头部时间文本
function ShowNow()
{
    var TimeNow = new Date();
    
    $("#TimeNow").text(TimeNow.toString().substr(0,7) + " " + TimeNow.getDate() + " " + TimeNow.getYear());
}

//首页的logo底部flash显示
function ShowFlashInHomePage(ImagePath, iWidth, iHeight)
{
    var FlashHtml = "<object id='objLotto' type='application/x-shockwave-flash' data='" + ImagePath + "' codebase='http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0' height='" + iHeight + "' width='" + iWidth + "' border='0' classid='clsid:D27CDB6E-AE6D-11CF-96B8-444553540000'>";
	FlashHtml = FlashHtml + "<param value='" + ImagePath + "' name='movie'/>";
	FlashHtml = FlashHtml + "<param value='High' name='quality'/>";
	FlashHtml = FlashHtml + "<param name='wmode' value='transparent'/>";
	FlashHtml = FlashHtml + "<embed src='" + ImagePath + "' height='" + iHeight + "' width='" + iWidth + "' quality='high' pluginspage='http://www.macromedia.com/go/getflashplayer' type='application/x-shockwave-flash' wmode='transparent'></embed>";
	FlashHtml = FlashHtml + "</object>";
	
	document.write(FlashHtml);
}

// ajax 的 WebService 的构造函数
function WebService(url,callback,pars){
    $.ajax({
      data:pars,
      url: url,
      type: "POST",
      contentType: "application/json;utf-8",
      dataType:'json',
      cache: false,
      success: function(json){
        callback(json.d);
      },
      error:function(xml,status){
        if(status=='error'){
            try{
                var json = eval('(' + xml.responseText + ')');
                alert(json.Message+'\n'+json.StackTrace);
            }
            catch(e){}
        }else{
            alert(status);
        }
      },
      beforeSend:function(xml){
        if(!pars)  xml.setRequestHeader("Content-Type", "application/json;utf-8")
      }
    });
}

// ajax 纯粹返回的构造函数
function WebRequestInfo(url,callback,pars)
{
    $.ajax({
       type: "POST",
       url: url,
       data: pars,
       success: function(msg){
         callback(msg);
       },
       error:function(xml,status){
        if(status=='error'){
            try{
                var json = eval('(' + xml.responseText + ')');
                alert(json.Message+'\n'+json.StackTrace);
            }
            catch(e){}
        }else{
            alert(status);
        }
      }
    }); 
}

function WebRequestInfoWithError(url,callback,pars,ErrorFun)
{
    $.ajax({
       type: "POST",
       url: url,
       data: pars,
       timeout:1000000,
       success: function(msg){
         callback(msg);
       },
       error:function(xml,status){
         ErrorFun(xml, status);
      }
    }); 
}

function WebRequestInfoWithReturn(url,callback,pars)
{
    $.ajax({
       type: "POST",
       url: url,
       data: pars,
       success: function(msg){
         return msg;
       }
    });
}

function WebRequestInfoSynchro(url, callback, pars) {
    $.ajax({
        async: false,
        type: "POST",
        url: url,
        data: pars,
        success: function(msg) {
            callback(msg);
        },
        error: function(xml, status) {
            if (status == 'error') {
                try {
                    var json = eval('(' + xml.responseText + ')');
                    alert(json.Message + '\n' + json.StackTrace);
                }
                catch (e) { }
            } else {
                alert(status);
            }
        }
    });
} 

function LatestActivityRefresh()
{
    WebRequestInfo("/Common/XmlHttpRequest.aspx?type=LatestActivity&checkvalue=1",function(obj){LatestActivityRefreshHandle(obj);}, "");
}

function LatestActivityRefreshHandle(objResult){
    if(objResult)
    {
        var result = objResult;
	    if(result!="")
	    { 
	        var s = "";
		    var allArray = result.split("|"); 
            var thisArray;
            for(var i = 0; i < allArray.length; i++) 
            {
		        thisArray = allArray[i].split(",");
		        s += "<div style=\"border-bottom: 1px dotted #CCCCCC;margin-top:2px;margin-bottom:2px;padding-bottom:2px; width:99%;\"><div style=\"float:left; width:40px;\"><img src=\""+ thisArray[0].toString() +"\" width=\"35\" height=\"35\" alt=\"\" /></div><div style=\"float:left;\"><div><img style=\"vertical-align:middle;\" src=\""+thisArray[1].toString()+"\" width=\"30\" height=\"15\" alt=\""+thisArray[4].toString()+"\"/> From "+ thisArray[5].toString() +" , "+ thisArray[6].toString() +"</div><div style=\"padding-top:3px;\">"+ thisArray[2].toString() +"</div><div style=\"padding-top:3px;\">"+ thisArray[3].toString()  +" "+ thisArray[7].toString() +"</div></div></div>";                
            }
            document.getElementById("div1").innerHTML = s;
            //$("#div1").html(s);
	    }
    }
}

var time = 16;

function LatestActivityCount()
{
    time = time - 1;
    $("#DivLeft").text("refresh in " + time + " seconds");
    if(time == 0)
    {
        time = 16;
        LatestActivityRefresh();
    }
}

function CreateClassifiedsFlash(ImagePath, iWidth, iHeight, LinkUrl)
{
	var FlashHtml = "<object id='objLotto' type='application/x-shockwave-flash' data='" + ImagePath + "' codebase='http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0' height='" + iHeight + "' width='" + iWidth + "' border='0' classid='clsid:D27CDB6E-AE6D-11CF-96B8-444553540000'>";
	FlashHtml = FlashHtml + "<param value='" + ImagePath + "' name='movie'/>";
	FlashHtml = FlashHtml + "<param value='High' name='quality'/>";
	FlashHtml = FlashHtml + "<param name='FlashVars' value='Classifiedflash=" + LinkUrl + "' />";
	FlashHtml = FlashHtml + "<embed FlashVars='Classifiedflash=" + LinkUrl + "' src='" + ImagePath + "' height='" + iHeight + "' width='" + iWidth + "' quality='high' pluginspage='http://www.macromedia.com/go/getflashplayer' type='application/x-shockwave-flash' wmode='transparent'></embed>";
	FlashHtml = FlashHtml + "</object>";
	
	document.write(FlashHtml);
}

function CreateFlashControl3(ImagePath, iWidth, iHeight, Code)
{
	var FlashHtml = "";
	FlashHtml = FlashHtml + "<object id='objLotto' onMouseUp=\"javascript:alert('aaa');\" type='application/x-shockwave-flash' data='" + ImagePath + "' codebase='http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0' height='" + iHeight + "' width='" + iWidth + "' border='0' classid='clsid:D27CDB6E-AE6D-11CF-96B8-444553540000'>";
	FlashHtml = FlashHtml + "<param value='" + ImagePath + "' name='movie'/>";
	FlashHtml = FlashHtml + "<param value='High' name='quality'/>";
	FlashHtml = FlashHtml + "<param name='wmode' value='transparent'/>";
	FlashHtml = FlashHtml + "<embed src='" + ImagePath + "' height='" + iHeight + "' width='" + iWidth + "' quality='high' pluginspage='http://www.macromedia.com/go/getflashplayer' type='application/x-shockwave-flash' wmode='transparent'></embed>";
	FlashHtml = FlashHtml + "</object>";
	
	return FlashHtml;
}

function ShowFirstFlashAndClick(Url, Code, DivID)
{
    $("#" + DivID).html(CreateFlashControl3(Url,'561','160',Code));
}

function ShowSecondFlashAndClick(Url, Code, DivID)
{
	$("#" + DivID).html(CreateFlashControl3(Url,'190','88',Code));
}

function ShowThirdFlashAndClick(Url, Code, DivID)
{
	$("#" + DivID).html(CreateFlashControl3(Url,'190','440',Code));
}

function ShowFourthFlashAndClick(Url, Code, DivID)
{
	$("#" + DivID).html(CreateFlashControl3(Url,'190','133',Code));
}

function ShowFifthFlashAndClick(Url, Code, DivID)
{
	$("#" + DivID).html(CreateFlashControl3(Url,'190','440',Code));
}

function GetUserInfo()
{
    WebRequestInfo("/WebService/XMLReturn2.aspx?action=getuserinfo&value=1&time=" + escape(new Date()),function(obj){GetUserInfoHandle(obj);}, "");
}

function GetUserInfoHandle(objResult){
    if(objResult)
    {
        var result = objResult;
	
	    if(result!="")
	    { 
		    var info = result.split("|");
            $("#Firstname").text(info[0]);
	    }
    }
}

function ShowLottoFlashInHomePage(ImagePath, iWidth, iHeight)
{
	var FlashHtml = "<object id='objLotto' type='application/x-shockwave-flash' data='" + ImagePath + "' codebase='http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0' height='" + iHeight + "' width='" + iWidth + "' border='0' classid='clsid:D27CDB6E-AE6D-11CF-96B8-444553540000'>";
	FlashHtml = FlashHtml + "<param value='" + ImagePath + "' name='movie'/>";
	FlashHtml = FlashHtml + "<param value='High' name='quality'/>";
	FlashHtml = FlashHtml + "<param name='wmode' value='transparent'/>";
	FlashHtml = FlashHtml +	"<param name=\"FlashVars\" value=\"ball1=3&ball2=10&ball3=13&ball4=18&ball5=24&ball6=31\" />";
	FlashHtml = FlashHtml + "<embed FlashVars=\"ball1=3&ball2=10&ball3=13&ball4=18&ball5=24&ball6=31\" src='" + ImagePath + "' height='" + iHeight + "' width='" + iWidth + "' quality='high' pluginspage='http://www.macromedia.com/go/getflashplayer' type='application/x-shockwave-flash' wmode='transparent'></embed>";
	FlashHtml = FlashHtml + "</object>";
	
	document.write(FlashHtml);
}

function GoToPlaceAdvertising(Urlval)
{
    var _PageType = "";
    window.location.href = Urlval;
}

function isIE()
{
	if(document.all) return true;
	return false;
}

function numkeypress(evnt)
{
	var key;
	if (isIE()) 
	{
		key = event.keyCode;
	}
	else
	{
		key = evnt.charCode;
	}
    if((key<48&&key!=46&&key!=45)||key>57)
    {
        event.keyCode=0;
    }
 }
 
function openWinnerPhoto(val,GameID, GameNum, Username)
{
    OpenOrClose("WinnerAlbum"+val);
	var HtmlContent = document.getElementById("WinnerAlbum"+val).innerHTML;	
	if(HtmlContent == "")
	{
		HtmlContent = "<iframe id='iframe"+val+"' name='iframe"+val+"' src='../Common/PhotoAlbum.aspx?gameid="+GameID+"&gamenum="+GameNum+"&username="+Username+"&record="+val+"' frameborder='0' width='100%' height='100%' scrolling='no'></iframe>";
		document.getElementById("WinnerAlbum"+val).innerHTML = HtmlContent;
		document.frames("iframe"+ val).document.location.reload();
	}
} 
 
function ResetFrameSize(frameName)
{
    var frm = document.getElementById(frameName);
    var subWeb = document.frames ? document.frames[frameName].document : frm.contentDocument;
    if(frm != null && subWeb != null)
    {
        frm.height = subWeb.body.scrollHeight;
    }
}

function IeTrueBody(){//判断头部是否有标准声明
    return (document.compatMode && document.compatMode!="BackCompat")? document.documentElement : document.body
}

function ShowChatIcon()
{
    var scrollTop = 0, scrollLeft = 0;        
    scrollTop = IeTrueBody().scrollTop;
    if( isNaN(scrollTop) || scrollTop < 0 ){ scrollTop = 0 ;}    
    scrollLeft = IeTrueBody().scrollLeft;
    if( isNaN(scrollLeft) || scrollLeft < 0 ){ scrollLeft = 0 ;}

    var obj = document.getElementById("divChat");
    var x=5, y=10;
    //obj.style.position="absolute";
    //alert(scrollLeft);
    x=x+scrollLeft;
    y=y+scrollTop;
    obj.style.left=x+"px";
    obj.style.top=y+"px";
}

function showLeftTime(intleftSecond, divName, hidName)
{
    var leftSecond;
    divNamea = divName;
	leftSecond = intleftSecond;
	document.getElementById(hidName).value = leftSecond;
	setInterval("calculateTime('" + hidName + "','" + divName + "')",1000);
}

function calculateTime(hidName, divName)
{
	//alert(leftSecond);
	leftSecond = document.getElementById(hidName).value;
	if(leftSecond == 1)
	{
		//alert(intleftSecond);
		window.location.reload();
	}
	if(leftSecond > 0)
	{
		intleftSecond = leftSecond;
		iDay = Math.floor(intleftSecond / (24 * 60 * 60));
	    if (iDay < 10) 
	    {
	      strDay = "0" + String(iDay);
	    }
	    else
	    {
	      strDay = String(iDay);
	    }
	
	    iLeft = intleftSecond % (24 * 60 * 60);
	    iHour = Math.floor(iLeft / (60 * 60));
	    if (iHour < 10)
	    {
	      strHour = "0" + String(iHour);
	    }
	    else
	    {
	      strHour = String(iHour);
	    }
	
	    iLeft = intleftSecond % (60 * 60);
	    iMin = Math.floor(iLeft / 60);
	    if (iMin < 10) 
	    {
	      strMin = "0" + String(iMin);
	    }
	    else
	    {
	      strMin = String(iMin);
	    }
	    
	    iLeft = (iLeft % (60)).toFixed(0);
	    iSec = Math.floor(iLeft);
	    if (iSec < 10) 
	    {
	      strSec = "0" + String(iSec);
	    }
	    else
	    {
	      strSec = String(iSec);
	    }
	    strSecondLeft = strDay + ":" + strHour + ":" + strMin + ":" + strSec;
	    document.getElementById(divName).innerHTML = strSecondLeft;
		leftSecond = leftSecond - 1;
		document.getElementById(hidName).value = leftSecond;
		intleftSecond=intleftSecond-1;
	}
}

function calculateTime2(leftSecond)
{
	if(leftSecond == 1)
	{
		window.location.reload();
	}
	
	if(leftSecond > 0)
	{
		intleftSecond = leftSecond;
		iDay = Math.floor(intleftSecond / (24 * 60 * 60));
	    if (iDay < 10) 
	    {
	      strDay = "0" + String(iDay);
	    }
	    else
	    {
	      strDay = String(iDay);
	    }
	
	    iLeft = intleftSecond % (24 * 60 * 60);
	    iHour = Math.floor(iLeft / (60 * 60));
	    if (iHour < 10)
	    {
	      strHour = "0" + String(iHour);
	    }
	    else
	    {
	      strHour = String(iHour);
	    }
	
	    iLeft = intleftSecond % (60 * 60);
	    iMin = Math.floor(iLeft / 60);
	    if (iMin < 10) 
	    {
	      strMin = "0" + String(iMin);
	    }
	    else
	    {
	      strMin = String(iMin);
	    }
	    
	    strSecondLeft = strDay + "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" + strHour + "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" + strMin;
	    
	    return strSecondLeft;
	}
}

function OpenOrClose(objID)
{
    $("#" + objID).toggle();
}

function AllwaysOpen(objID) {
    if (document.getElementById(objID).style.display == 'none') {
        document.getElementById(objID).style.display = 'block';
    }
}

$(document).ready(function(){
    ShowNow();
    
    if($("#Firstname").attr("id") == "Firstname")
    {
        $('body').oneTime('1s', GetUserInfo);
    }
    
    if($("#div1").attr("id") == "div1")
    {
        $('body').everyTime('1s',LatestActivityCount);
    }
    
    if($("#hidFrontRowTimeLeft").attr("id") == "hidFrontRowTimeLeft")
    {
        FrontRowTimeLeft = Math.floor($("#hidFrontRowTimeLeft").val());
        
        if(FrontRowTimeLeft > 0)
        {
            $("#FrontRowTimeLeft").html(calculateTime2(FrontRowTimeLeft));
            FrontRowTimeLeft = FrontRowTimeLeft - 1;
        }
    }
});
