﻿/* 正規表示式-加上 commas(",") 符號
 *
 * Author: Victor Chen
 * Date: 2007/05/06
 * Update Author: Victor Chen
 * Update 2007/05/06
 */
function addCommas(strValue) {
    var objRegExp  = new RegExp('(-?[0-9]+)([0-9]{3})');
    while(objRegExp.test(strValue)) {
        strValue = strValue.replace(objRegExp, '$1,$2');
    }
    return strValue;
}

/* 正規表示式-移除 commas符號(",")
 *
 * Author: Victor Chen
 * Date: 2007/05/06
 * Update Author: Victor Chen
 * Update 2007/05/06
 */
function removeCommas(strValue) {
    var objRegExp = /,/g;
    return strValue.replace(objRegExp, '');
}

/* 正規表示式-移除所有空白字元及符號("\s", "\w", "\W", "\b")
 *
 * Author: Victor Chen
 * Date: 2007/05/06
 * Update Author: Victor Chen
 * Update 2007/05/06
 */
function trim(strValue) {
	var objRegExp = /^(\s*)$/;
	if(objRegExp.test(strValue)) {
	   strValue = strValue.replace(objRegExp, '');
	   if(strValue.length == 0)
	      return strValue;
	}
	objRegExp = /^(\s*)([\W\w]*)(\b\s*$)/;
	if(objRegExp.test(strValue)) {
	   strValue = strValue.replace(objRegExp, '$2');
	}
	return strValue;
}

/* onKeyDown event Escape Escape Illegal Input Value
 * Parameter: Form.[TagObject]
 *            Event
 *
 * Author: Victor Chen
 * Date: 2007/05/06
 * Update Author: Victor Chen
 * Update 2007/06/05
 */
function validateOnKD(fld, e) {
	var keyCode = (document.all) ? e.keyCode : e.which;

	//Escape Ctrl + V
	return (keyCode!=86);
}

/* 以 onKeyPress event Escape Illegal Input Value
 * Parameter: Form.[TagObject]
 *            Event
 *
 * Author: Victor Chen
 * Date: 2007/05/06
 * Update Author: Victor Chen
 * Update 2007/05/06
 */
function validateOnKP(fld, e, selster) {
    var keyCode = (document.all) ? e.keyCode : e.which;
	
	//判斷當有輸入資料且選擇開始的位置是最開頭 就不准輸入0
	if(fld.value.length>0 && selster==0)
	{
	    if(keyCode==48) return false;
	}
	
    //Permit Enter and BackSpace
    if (keyCode == 13 || keyCode == 8) return true;

    //Escape Prefix 0
   	if (/^$/.test(removeCommas(fld.value)) && /0/.test(String.fromCharCode(keyCode))) return false;

    //Escape NaN Number
    if (/[^0-9]/.test(String.fromCharCode(keyCode))) return false;

	return true;
}
function validateOnKPPhone(fld, e, from) {
    var keyCode = (document.all) ? e.keyCode : e.which;
    var fromWhich = from;

    //Permit Enter and BackSpace for stake and score
    if ((keyCode == 13 || keyCode == 8 || keyCode == 45) && (fromWhich == 'stakeField' || fromWhich == 'scoreField')) return true;
    //Permit Enter and BackSpace and decimal and left arrow and right arrow for odds and hdp
    if ((keyCode == 13 || keyCode == 8 || keyCode == 46 || keyCode == 45 || keyCode == 39 || keyCode == 37) && (fromWhich == 'oddsField' || fromWhich == 'hdpField')) return true;

    //Escape NaN Number
    if (/[^0-9]/.test(String.fromCharCode(keyCode))) return false;


	return true;
}
/* 以 onKeyUp event Count Current Payout
 * Parameter: Form.[TagObject]
 *            Event
 *
 * Author: Victor Chen
 * Date: 2007/05/06
 * Update Author: Victor Chen
 * Update 2007/05/06
 */
function payOutOnKU(fld, e) {
    fld.value = addCommas(removeCommas(fld.value));

	//Empty Input
	if(/^$/.test(removeCommas(fld.value))) {
	    if (window.top.siteMode == "1")
	    {
	        document.getElementById('payOut_P').innerHTML = '';
	    }
	    else
		{
		    document.getElementById('payOut').innerHTML = '';
		}
	}
	else {
        var bodds;
        var bettype;
        var sitetype;
        var oddstype;

        if (window.top.SiteMode == "1")
        {
            bettype=document.getElementById('bettype_P').value;
            sitetype=document.getElementById('siteType_P').value;
            oddstype=document.getElementById('oddsType_P').value;
            
            switch(bettype)
            {
                case '1':
                case '7':
                    bodds=document.getElementById("bp_odds3").value;
                    break;
                case "3":
                case "8":
                    bodds=document.getElementById("bp_odds2").value;
                    break;
                default:
                    bodds=document.getElementById("bp_odds1").value;
                    break;
            }
        }
        else
        {
            bettype=document.getElementById('bettype').value;
            sitetype=document.getElementById('siteType').value;
            oddstype=document.getElementById('oddsType').value;
        }

	    //if((bettype == 1 || bettype == 2 || bettype == 3 || bettype == 7 || bettype == 8 || bettype == 20) && (sitetype != "DECIMAL" && sitetype != "DECIADD")) {
	    if((bettype == 1 || bettype == 2 || bettype == 3 || bettype == 7 || bettype == 8 || bettype == 20) && (oddstype != "1")) {
	        // 2 choose 1 Payout = stake * (1 + odds)
	        if (window.top.SiteMode == "1")
	            document.getElementById('payOut_P').innerHTML = addCommas((removeCommas(fld.value) * (1 + Math.abs(removeCommas(bodds)))).toFixed(2));
            else
                document.getElementById('payOut').innerHTML = addCommas((removeCommas(fld.value) * (1 + Math.abs(removeCommas(document.getElementById('bodds').innerHTML)))).toFixed(2));

	        //string = document.getElementById('odds').innerHTML;
	    }
	    else {
	        // Other Payout = stake * odds;
	        if (window.top.SiteMode == "1")
	            document.getElementById('payOut_P').innerHTML = addCommas((removeCommas(fld.value) * Math.abs(removeCommas(bodds))).toFixed(2));
	        else
	            document.getElementById('payOut').innerHTML = addCommas((removeCommas(fld.value) * Math.abs(removeCommas(document.getElementById('bodds').innerHTML))).toFixed(2));
	    }
	}
}

function payOutOnKUOT(fld, e) {
    fld.value = addCommas(removeCommas(fld.value));
	//Empty Input
	if(/^$/.test(removeCommas(fld.value))) {
		if (window.top.SiteMode == "1")
		    document.getElementById('payOut_P').innerHTML = '';
		else
		    document.getElementById('payOut').innerHTML = '';
	}
	else {
        // Other Payout = stake * odds;
        if (window.top.SiteMode == "1")
 	        document.getElementById('payOut_P').innerHTML = addCommas((removeCommas(fld.value) * Math.abs(removeCommas(document.getElementById('odds').value))).toFixed(2));
        else
	        document.getElementById('payOut').innerHTML = addCommas((removeCommas(fld.value) * Math.abs(removeCommas(document.getElementById('bodds').innerHTML))).toFixed(2));

	}
}

function payOutOnKUPhone(fld, e) {
    fld.value = addCommas(removeCommas(fld.value));

	//Empty Input
	if(/^$/.test(removeCommas(fld.value))) {
		document.getElementById('payOut').innerHTML = '';
	}
	else {
	    if((document.getElementById('bettype').value == 1 || document.getElementById('bettype').value == 2 || document.getElementById('bettype').value == 3 || document.getElementById('bettype').value == 7 || document.getElementById('bettype').value == 8 || document.getElementById('bettype').value == 20) && (document.getElementById('siteType').value != "DECIMAL" && document.getElementById('siteType').value != "DECIADD")) {
	        // 2 choose 1 Payout = stake * (1 + odds)
	        document.getElementById('payOut').innerHTML = addCommas((removeCommas(fld.value) * (1 + Math.abs(removeCommas(document.getElementById('odds').value)))).toFixed(2));
	        //string = document.getElementById('odds').innerHTML;
	    }
	    else {
	        // Other Payout = stake * odds;
	        document.getElementById('payOut').innerHTML = addCommas((removeCommas(fld.value) * Math.abs(removeCommas(document.getElementById('odds').value))).toFixed(2));
	    }
	}
}



/* 用來處理 Bet 的格式(###,###) , 要放在 OnKeyup事件上
 * 如果多傳 Odd 和 Payout 的 HTML Object ID , 會一併把Payout算出來，並寫在Payout的那一個Object上
 *
 * Author: David Wu
 * Date: 2007/05/09
 * Update Author: David Wu
 * Update 2007/05/09
 */

function checkValue(obj,oddsID,payoutID)
{
    var strCheck = "0123456789";

    var strClean = "";
    var bFlag = true;
    for(var i=0;i<obj.value.length;i++)
    {
        if(obj.value.charAt(i) == ".")
            break;

        if(obj.value.charAt(i) != "," && strCheck.indexOf(obj.value.charAt(i)) != -1)
            strClean += obj.value.charAt(i);
    }

    var strFormated = addCommas(strClean);
    obj.value = strFormated;

    if(oddsID != null && oddsID != "" && payoutID != null && payoutID != "")
    {
        var oddsObject = document.getElementById(oddsID);
        var payoutObject = document.getElementById(payoutID);

        var oddsValue;
        if(oddsObject.tagName == "INPUT")
            oddsValue = oddsObject.value;
        else
            oddsValue = oddsObject.innerHTML;

        if(!isNaN(oddsValue) && !isNaN(strClean))
        {
            var dValue = parseFloat(oddsValue) * parseFloat(strClean);
            var sValue = String(dValue.toFixed(2));

            var dot = sValue.split(".");
            var sResult = addCommas(dot[0]) + "." + dot[1];

            if(!isNaN(dValue))
            {
                if(payoutObject.tagName == "INPUT")
                    payoutObject.value = sResult;
                else
                    payoutObject.innerHTML = sResult;
            }
            else
            {
                if(payoutObject.tagName == "INPUT")
                    payoutObject.value = "";
                else
                    payoutObject.innerHTML = "";
            }
        }
        else
        {
            if(payoutObject.tagName == "INPUT")
                payoutObject.value = "";
            else
                payoutObject.innerHTML = "";
        }
    }
}

/* 用來處理輸入 Bet 的欄位的字元 , 不允許小數點的輸入 , 要放在 OnKeypress事件上
 *
 *
 * Author: David Wu
 * Date: 2007/05/09
 * Update Author: David Wu
 * Update 2007/05/09
 */

function checkKeyPress(obj,e ,selster)
{
    var keyCode = (document.all) ? e.keyCode : e.which;
    //判斷當有輸入資料且選擇開始的位置是最開頭 就不准輸入0
	if(obj.value.length>0 && selster==0)
	{
	    if(keyCode==48) return false;
	}

    var strCheck = '0123456789';

    var whichCode = (document.all) ? e.keyCode : e.which;
    if (whichCode == 13 || whichCode == 8) return true;  // Enter

    key = parseInt(String.fromCharCode(whichCode),10);  // Get key value from key code
    if (strCheck.indexOf(key) == -1) return false;  // Not a valid key

    if(obj.value.length==0 && key == "0") return false;

    return true;
}

// Check Email Fromat
//Author : Brian Yang  (Copy from Google)
//Date : 2007/10/17
//
function emailCheck (emailStr) {
/* The following pattern is used to check if the entered e-mail address
  fits the user@domain format.  It also is used to separate the username
  from the domain. */
var emailPat=/^(.+)@(.+)$/
/* The following string represents the pattern for matching all special
  characters.  We don't want to allow special characters in the address.
  These characters include ( ) < > @ , ; : \ " . [ ]    */
var specialChars="\\(\\)<>@,;:\\\\\\\"\\.\\[\\]"
/* The following string represents the range of characters allowed in a
  username or domainname.  It really states which chars aren't allowed. */
var validChars="\[^\\s" + specialChars + "\]"
/* The following pattern applies if the "user" is a quoted string (in
  which case, there are no rules about which characters are allowed
  and which aren't; anything goes).  E.g. "jiminy cricket"@disney.com
  is a legal e-mail address. */
var quotedUser="(\"[^\"]*\")"
/* The following pattern applies for domains that are IP addresses,
  rather than symbolic names.  E.g. joe@[123.124.233.4] is a legal
  e-mail address. NOTE: The square brackets are required. */
var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/
/* The following string represents an atom (basically a series of
  non-special characters.) */
var atom=validChars + '+'
/* The following string represents one word in the typical username.
  For example, in john.doe@somewhere.com, john and doe are words.
  Basically, a word is either an atom or quoted string. */
var word="(" + atom + "|" + quotedUser + ")"
// The following pattern describes the structure of the user
var userPat=new RegExp("^" + word + "(\\." + word + ")*$")
/* The following pattern describes the structure of a normal symbolic
  domain, as opposed to ipDomainPat, shown above. */
var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$")


/* Finally, let's start trying to figure out if the supplied address is
  valid. */

/* Begin with the coarse pattern to simply break up user@domain into
  different pieces that are easy to analyze. */
var matchArray=emailStr.match(emailPat)
if (matchArray==null) {
 /* Too many/few @'s or something; basically, this address doesn't
    even fit the general mould of a valid e-mail address. */
       //alert("Email address seems incorrect (check @ and .'s)")
       return false
}
var user=matchArray[1]
var domain=matchArray[2]

// See if "user" is valid
if (user.match(userPat)==null) {
   // user is not valid
   //alert("The username doesn't seem to be valid.")
   return false
}

/* if the e-mail address is at an IP address (as opposed to a symbolic
  host name) make sure the IP address is valid. */
var IPArray=domain.match(ipDomainPat)
if (IPArray!=null) {
   // this is an IP address
         for (var i=1;i<=4;i++) {
           if (IPArray[i]>255) {
               //alert("Destination IP address is invalid!")
               return false
           }
   }
   return true
}

// Domain is symbolic name
var domainArray=domain.match(domainPat)
if (domainArray==null) {
       alert("The domain name doesn't seem to be valid.")
   return false
}

/* domain name seems valid, but now make sure that it ends in a
  three-letter word (like com, edu, gov) or a two-letter word,
  representing country (uk, nl), and that there's a hostname preceding
  the domain or country. */

/* Now we need to break up the domain to get a count of how many atoms
  it consists of. */
var atomPat=new RegExp(atom,"g")
var domArr=domain.match(atomPat)
var len=domArr.length
if (domArr[domArr.length-1].length<2 ||
   domArr[domArr.length-1].length>4) {
  // the address must end in a two letter or three letter word.
  //alert("The address must end in a three-letter domain, or two letter country.")
  return false
}

// Make sure there's a host name preceding the domain.
if (len<2) {
  var errStr="This address is missing a hostname!"
  //alert(errStr)
  return false
}

// If we've gotten this far, everything's valid!
return true;
}

function gotoSportsBookPage()
{
    if(parent.top.LastSelectedMenu!=null)
    {
        parent.top.LastSelectedMenu=0;
	parent.top.LastSelectedSport=-1;
    }
    parent.leftFrame.location="leftAllInOne.aspx";
    parent.mainFrame.location="UnderOver.aspx?Market=t&DispVer=new";
}

// open streaming window
function openStreaming(pStreamingId) {
    /*if (window.top.StreamingFrame != null) {
		window.top.StreamingFrame.close();
	}
    if (pStreamingId != null) {
		window.top.StreamingFrame = window.top.window.open("StreamingFrame.aspx?StreamingId=" + pStreamingId, "StreamingFrame", "top=200,left=300,height=520,width=525,status=no,toolbar=no,menubar=no,resizable=yes,location=no");
	} else {
		window.top.StreamingFrame = window.top.window.open("StreamingFrame.aspx", "StreamingFrame", "top=200,left=300,height=630,width=800,status=no,toolbar=no,menubar=no,resizable=yes,location=no");
	}*/
	if (window.top.StreamingFrame == null || window.top.StreamingFrame.closed)
	{
	    window.top.StreamingFrame = window.top.window.open("StreamingFrame.aspx", "StreamingFrame", "top=200,left=300,height=630,width=800,status=no,toolbar=no,menubar=no,resizable=yes,location=no");
	}
	else
	{
	    window.top.StreamingFrame.Resize1(false);
	    window.top.StreamingFrame.focus();
	}
}

//Scott JS Marquee
function SunPlus_Marquee() {
	var _this = this;
	this.marquee_mouse = 1;
	this.scroll_speed = 1;
	this.marquee_flag = true;
	this.scrollerwidth = 500;
	this.DivElm = null;

	this.Mymarquee_scroll = function(){
		marquee_scroll()
	}

	function marquee_scroll() {
		var tmp;
		tmp = _this.DivElm.style;
		if (_this.marquee_mouse && _this.marquee_flag) {
			tmp.left = parseInt(tmp.left,10) - _this.scroll_speed;
			if (parseInt(tmp.left,10) <= -_this.DivElm.offsetWidth) {
				tmp.left = _this.scrollerwidth;
			}
		}
		window.setTimeout(marquee_scroll ,100);
	}
}


function isNum(N){
	numtype = "0123456789";
	for (i=0; i < N.length; i++) { //檢討是否有不在 0123456789之內的字
		if (numtype.indexOf(N.substring(i, i+1)) < 0)
			return false;//是的話....結束迴圈;傳回false
	}
	return true;
}

function check_email ( email )	//檢查email信箱的正確性
{
   var len = email.length;
   if(len==0)
      return false;
   for(var i=0;i<len;i++)
   {  var c= email.charAt(i);
      if(!((c>="A"&&c<="Z")||(c>="a"&&c<="z")||(c>="0"&&c<="9")||(c=="-")||(c=="_")||(c==".")||(c=="@")))
         return false;
   }
   if((email.indexOf("@")==-1)||(email.indexOf("@")==0)||(email.indexOf("@")==(len-1)))
      return false;
   if((email.indexOf("@")!=-1)&&(email.substring(email.indexOf("@")+1,len).indexOf("@")!=-1))
      return false;
   if((email.indexOf(".")==-1)||(email.indexOf(".")==0)||(email.lastIndexOf(".")==(len-1)))
      return false;

   ///////////////////////////////////////

   var tail1,tail2;
   len = email.length;
   tail1 = email.substring(email.indexOf("@")+1,len)
   var posi = tail1.indexOf(".");
   while( posi > 0 ) {
      tail2 = tail1.substring(0, tail1.indexOf(".") )
      len = tail2.length;

      if (len < 2)
         return false; // 不可過短

      len = tail1.length;
      tail1 = tail1.substring(tail1.indexOf(".")+1,len )

      posi = tail1.indexOf(".");

   }

   len = tail1.length;
   if (len < 2)
      return false; // 不可過短

   if ( isNum(tail1) )
      return false; // 最後一段 不可全為數字


   ///////////////////////////////////////

   if( (email.indexOf('@.')) >= 0 ) // 不可 為 abc@.com
      return false;
   //alert(email);
   return true;
}


function replaceSubstring(inputString, fromString, toString) {
   // Goes through the inputString and replaces every occurrence of fromString with toString
   var temp = inputString;
   if (fromString == "") {
      return inputString;
   }
   if (toString.indexOf(fromString) == -1) { // If the string being replaced is not a part of the replacement string (normal situation)
      while (temp.indexOf(fromString) != -1) {
         var toTheLeft = temp.substring(0, temp.indexOf(fromString));
         var toTheRight = temp.substring(temp.indexOf(fromString)+fromString.length, temp.length);
         temp = toTheLeft + toString + toTheRight;
      }
   } else { // String being replaced is part of replacement string (like "+" being replaced with "++") - prevent an infinite loop
      var midStrings = new Array("~", "`", "_", "^", "#");
      var midStringLen = 1;
      var midString = "";
      // Find a string that doesn't exist in the inputString to be used
      // as an "inbetween" string
      while (midString == "") {
         for (var i=0; i < midStrings.length; i++) {
            var tempMidString = "";
            for (var j=0; j < midStringLen; j++) { tempMidString += midStrings[i]; }
            if (fromString.indexOf(tempMidString) == -1) {
               midString = tempMidString;
               i = midStrings.length + 1;
            }
         }
      } // Keep on going until we build an "inbetween" string that doesn't exist
      // Now go through and do two replaces - first, replace the "fromString" with the "inbetween" string
      while (temp.indexOf(fromString) != -1) {
         var toTheLeft = temp.substring(0, temp.indexOf(fromString));
         var toTheRight = temp.substring(temp.indexOf(fromString)+fromString.length, temp.length);
         temp = toTheLeft + midString + toTheRight;
      }
      // Next, replace the "inbetween" string with the "toString"
      while (temp.indexOf(midString) != -1) {
         var toTheLeft = temp.substring(0, temp.indexOf(midString));
         var toTheRight = temp.substring(temp.indexOf(midString)+midString.length, temp.length);
         temp = toTheLeft + toString + toTheRight;
      }
   } // Ends the check to see if the string being replaced is part of the replacement string or not
   return temp; // Send the updated string back to the user
}

function currencyFormat(fld, milSep, decSep, e) {
	var sep = 0;
	var key = '';
	var i = j = 0;
	var len = len2 = 0;
	var strCheck = '0123456789';
	var aux = aux2 = '';
	var whichCode = (document.all) ? e.keyCode : e.which;
	if (whichCode == 8) fld.value=''; 
	if (whichCode == 13) return true;  // Enter

	key = parseInt(String.fromCharCode(whichCode),10);  // Get key value from key code
	if (strCheck.indexOf(key) == -1) return false;  // Not a valid key
	len = fld.value.length;
	for(i = 0; i < len; i++)
	if ((fld.value.charAt(i) != '0') && (fld.value.charAt(i) != decSep)) break;
	aux = '';

	for(; i < len; i++)
	if (strCheck.indexOf(fld.value.charAt(i))!=-1) aux += fld.value.charAt(i);
	aux += key;
	len = aux.length;
	if (len == 0) fld.value = '';
	if (len >0) {
		aux2 = '';
		for (j = 0, i = len-1; i >= 0; i--) {
			if (j == 3) {
				aux2 += milSep;
				j = 0;
			}
			aux2 += aux.charAt(i);
			j++;
		}
		fld.value = '';
		len2 = aux2.length;
		for (i = len2-0 ; i >= 0; i--)
		fld.value += aux2.charAt(i);
		fld.value += aux.substr(len,len) ;
	}
	return false;
}

/*
 * Author: Victor Chen 
 * Date: 2007/05/06
 * Update Author: Victor Chen
 * Update 2007/05/06
 */							
function countPayOut() {
	var stake = trim(removeCommas(document.getElementById('OTStake').value));
	var odds = trim(removeCommas(document.getElementById('ot_spOddsValue').innerHTML));
	if(stake.length != 0 && odds.length != 0) {
		document.getElementById('OTpayOut').innerHTML = addCommas((stake * odds).toFixed(2));
	}
	else {
		document.getElementById('OTpayOut').innerHTML = '';
	}
}

function onKeyDownFunc(whereTo,e) {
    var keyCode = (document.all) ? e.keyCode : e.which;
    if(keyCode==9){
        var destination = document.getElementById(whereTo);
        if (destination != null) {
            destination.focus();
            destination.select();
        }
    }
}