﻿var array = new Array();

$(document).ready(function(){
     InitTxt();   //文本框效果
     GetGame();   //初始化游戏名
     GetCountry();      //绑定城市
     $('#btnBuy').click(BuyGold);
     $('#gameName').change(function(){                   //服务器联动
        onGameChange();  
    });
 
   $('#gameServer').change(function(){                //金币（Product)联动
     onServerChange()
   });
   
   $('#gameProduct').change(function(){                 //价格联动
     onProductChange();
   });
 });
 
 function onGameChange()
 {
   var gameCode =  $('#gameName')[0].value;
      $('#gameServer').empty();
      $('#gameProduct').empty();
      array = new Array();
       $('#productList').empty();
      $('#price').text('0.00'); 
      $('#gameProduct').append('<option>--Select your product--</option>');
      if(gameCode ==null || gameCode==-1)
      {
        $('#gameServer').append('<option>--Select your server--</option>');
        return;
      }
      GetServer(gameCode);
 }
 
 function onServerChange()
 {
   var serverCode = $('#gameServer')[0].value;
     $('#gameProduct').empty();
     array = new Array();
     $('#price').text('0.00'); 
     if(serverCode ==null || serverCode ==- 1)
     {
       $('#gameProduct').append('<option>--Select your product--</option>');
       return;
     }
      GetProduct(serverCode);
 }
 
 function onProductChange()
 {
     var price = $('#gameProduct')[0].value;
      $('#price').empty();
      if(price == "-1") 
      {
         $('#price').text("0.00");
         return;
      }
      $('#price').text(price);
     
 }
 
 function GetGame()
 {
 $('#gameName').append('<option>--------Loading--------</option>');
   $.ajax({
    url:'/GetSiteGame.ashx',
    type:'get',
    complete:function(){$('#gameName>option:first').remove();},
    success:BindGame
   });
 }
 
 function BindGame(xml)
 {
 $('#gameName').append('<option value=\"-1\">--Select your game name--</option>');
   $(xml).find('Game').each(function(){
     var gameName = $(this).find('GameName').text();
     var gameCode = $(this).find('GameCode').text();
     $('#gameName').append('<option value = ' + gameCode + '>' + gameName + '</option>');
   });
   var startIndex =(window.location).toString().indexOf('Cheap.');
   if(startIndex <= 0 || startIndex ==null || startIndex == 'undefined' || startIndex == '')
   { 
    $('#gameName').val(-1);
    return;
   }
   else
   { 
    var code = (window.location).toString().substr(startIndex + 6,3);
    $('#gameName').val(code);
    onGameChange();
   } 
 }
 
 function GetServer(code)
 {
   
   $('#gameServer').append('<option>--------Loading--------</option>');
   $.ajax({
     url: '/GetGameServer.ashx',
     data:'gameCode=' + code,
     type:'get',
     complete:function(){ $('#gameServer>option:first').remove(); },
     success:BindServer  
   });
 }
 
 function BindServer(xml)
 {
   $('#gameServer').append('<option value=\"-1\">--Select your game server--</option>');
   $(xml).find('Server').each(function(){
      var serverName = $(this).find('ServerName').text();
      var serverCode = $(this).find('ServerCode').text();
      $('#gameServer').append('<option value = ' + serverCode + '>' + serverName + '</option>');
   });
   $('#gameServer').val(-1);
 }
 
 function GetProduct(servercode)
 {
   var moneyType = $('#hideMoneyType')[0].value; 
     
   $('#gameProduct').empty();
   $('#gameProduct').append('<option>--------Loading--------</option>');
   
   $.ajax({
     url:'/GetGoldProduct.aspx',
     data:'serverCode=' + servercode + '&moneyType='+ moneyType ,
     type:'get',
     success:BindProduct
   });
 }
 
 function BindProduct(xml)
 {      
 $('#gameProduct').append('<option value=\"-1\">-Select your product-</option>');
  var tbody='';
  var th='<tr>';
  var td='<tr>';
  var num = $(xml).find('Product').length;  //记录总数
  
   $(xml).find('Product').each(function(i){
     var productName = $(this).find('ProductName').text();
     var productPrice = $(this).find('SaleProductPrice').text();
     var productGuid = $(this).find('Guid').text();
     array.push(productGuid);
           
     $('#gameProduct').append('<option value = "' + productPrice + '">' + productName + '</option>');
     th += "<th><div id=\"" + productGuid + "\" onmouseover=\"setBgColor('" + productGuid  + "');\" onmouseout=\"rebackColor('" + productGuid + "');\"  onclick=\"setProduct('" + productGuid  + "');\" style=\" cursor:point;\" >" +  productName + "</div></th>";
     td += "<td><div id=\"" + productGuid + "\" onmouseover=\"setBgColor('" + productGuid  + "');\" onmouseout=\"rebackColor('" + productGuid + "');\" onclick=\"setProduct('" + productGuid  + "');\" style=\" cursor:point;\" >" + productPrice + "</div></td>";
     
     if( (i+1)%6 == 0)
     {
     tbody +=th + '</tr>' + td + '</tr>';
     th = '<tr>';
     td = '<tr>';
     }
     
     if(i == num-1 && num%6 > 0)
     {
       for(var j = 0; j < 6 - num%6 ; j++)
       {  
         th += "<th></th>";
         td += "<td></td>";
       } 
       tbody += th + '</tr>' + td + '</tr>';
     }
     
   });
   $('#VolumeDiscounttitle').show();
   $('#productList').empty();
   $('#gameProduct>option:first').remove();
   $('#productList').append("<div id=\"VolumeDiscounttitle\">Volume Discount</div><table class=\"VolumeDiscount\">" + tbody + "</table>");
   $('#gameProduct').val(-1);
   
   if($('#hideProduct')[0].value !='' && $('#hideProduct')[0].value != null && $('#hideProduct')[0].value != 'undefined')
   {
     $('#gameProduct')[0].selectedIndex = $('#hideProduct')[0].value;
     $('#hideProduct')[0].value ='';
     onProductChange();
   }
 }
 
 function setProduct(productGuide)
 {
    if(array.length > 0)
    {
      var index;
     for(var i = 0; i<array.length ;i++)
     {
       if(array[i] == productGuide)
       {
          index = i;
          break;
       }
     }
     $('#gameProduct')[0].selectedIndex = index + 1;
     onProductChange();
    }
 }
 
 function setBgColor(id)
 {
   $('#'+ id ).css('background','#FDFDE9');
 }
 
 function rebackColor(id)
 {
   $('#' + id).css('background','#E9E4DA');
 }
 
 function GetCountry()
 {
   $('#selCountry').append('<option value=-1>----Loading----</option>');
   $.ajax({
     url:'/GetCountry.ashx',
     type:'get',
     complete:function(){ $('#selCountry>option:first').remove();},
     success:BindCountry 
   });
 }
 
 function BindCountry(xml)
 {
  $('#selCountry').append('<option value=\"-1\">Select your country</option>');
   $(xml).find('Country').each(function(){
      var countryName = $(this).find('CountryName').text();
      $('#selCountry').append('<option value = ' + countryName + '>' + countryName + '</option>');
   });
   $('#selCountry').append('<option value =\"Other\">Other</option>');
   $('#selCountry').val(-1);
 }
 
 function ChangeMoney(moneyType)                                   //选择不同的money种类
{
     var serverCode = $('#gameServer')[0].value;
     $('#hideMoneyType')[0].value = moneyType;
     $('.moneyType').css('color','');
     $('#' + moneyType).css('color','red');
     if(serverCode ==null || serverCode ==- 1 || serverCode =='')
     {
       $('#gameProduct').append('<option value=-1>--Select your product--</option>');
       return;
     }
     
     var index = $('#gameProduct')[0].selectedIndex;
     $('#hideProduct')[0].value = index;
     $('#gameProduct').empty();
     array = new Array();
     $('#price').text('0.00'); 
     GetProduct(serverCode);
}

function InitTxt()
 {
  $('#txtDiscount').blur(function(){
 var discount = $('#txtDiscount')[0].value;
   
   discountCheck(discount);
 });
 }
 
 function BuyGold()                                    //Btn Buy Now
 {
   if(!$('#rbtnIsAccept').attr('checked'))
   {
     return;
   }
   
   var gameCode = $('#gameName')[0].value;
   var gameName = $('#gameName>option:selected').text();
   var serverCode = $('#gameServer')[0].value;
   var serverName = $('#gameServer>option:selected').text();
   var productValue = $('#gameProduct').val();
   
   var txtFullName = $('#txtFullName')[0].value;
   var txtCharacter = $('#txtCharacter')[0].value;
   var txtEmail = $('#txtEmail')[0].value;
  
   var txtNonUsPhone = $('#txtNonUsPhone')[0].value;
   txtNonUsPhone = (txtNonUsPhone == 'Non-US Phone'?'':txtNonUsPhone);
   
    var moneyType = $('#hideMoneyType')[0].value;
    var country = $('#selCountry')[0].value;
   var txtDiscount = $('#txtDiscount')[0].value;
   var payMethod = $("input[name=radPay][checked]").val();

   
   if(!drpCheck(gameCode,serverCode,productValue))
   return false;
   
   if(!fullNameCheck(txtFullName))
   return false;
   
   if(!characterCheck(txtCharacter))
   return false;
   
    if(!emailCheck(txtEmail))
   return false;
   
   if(!PhoneCheck(txtNonUsPhone))
   return false;
   
   if(!discountCheck(txtDiscount))
   return false;
   
  if(country =="-1")
  {
    alert('Error:Please select your country!'); 
    return false;
  }
   
    var index = $('#gameProduct')[0].selectedIndex;
   if(array.length <= 0 || index > array.length)
   return false;
   var productGuid = array[index-1];  
   
    SentDataToServer(gameCode,gameName,serverCode,serverName ,productGuid,payMethod,txtFullName,txtCharacter,txtEmail,country,txtNonUsPhone,moneyType);
   window.location.href = "/GoldOrderDetail.aspx";
 }
 
 function drpCheck(gameCode,serverCode,productValue)
{
  if(gameCode == null || gameCode ==-1)
  {
    alert('Error:Please select your game!'); 
    return false;
  }
  
  if(serverCode == null || serverCode ==-1)
  {
    alert('Error:Pleaser select server!');
    return false;
  }

  if(productValue == null || productValue == -1)
  {
   alert('Error:Please select your product!');
    return false;
  }
  return true;
}

function fullNameCheck(fName)
{
  if(fName == '' || fName.length > 30)
  {
   alert('Error:Please input your full name!');
   return false;
  }
  return true;
}

function characterCheck(character)
{
  if(character == '' || character.length > 30 )
  {
   alert('Error:Please input your character');
   return false;
  }
  return true;
}

function emailCheck (email) {
 var emailPat=/^(.+)@(.+)$/;
 var matchArray=email.match(emailPat);
 if (matchArray==null || email.length > 50) {
  alert('Error:Please input formate email');
 return false;
}
 return true;
}


function PhoneCheck(str)
{ 
   var reg=/^([0-9]|[\-])+$/g ;
   var marchArray = str.match(reg);
   
   if(str == 'Phone' || str == '' || str.length > 15 || marchArray == null)
   {
    $('#phoneerror').show();
    return false;
   }
   else
     $('#phoneerror').hide();
     return true;
}

function discountCheck(discount)   //折扣验证
{
  if(discount == 'Discount Coupon:' || discount == null || discount=='')
  return true;
  else 
  {
    var gameCode = $('#gameName')[0].value;
    $('#hideDiscount').show();
    var response = $.ajax({
     url:'/GoldCouponCheck.aspx',
     data:'couponCode=' + discount + '&gameCode=' + gameCode,
     type:'get',
     cache:'false',
     async:'false',
     complete:function(){$('#hideDiscount').hide();}
    }).responseText;
    if(response == 'wrong')
    {
      alert('This COUPON is error or has expired!');
      return false;
    }
    else
    return true;
  }
}

function SentDataToServer(gameCode,gameName,serverCode,serverName,productGuid,payMehtod,fullName,characterName,email,country,nonUsPhone,moneyType)
{
  $.ajax({
        url:'/GoldDataDispose.aspx',
        data:'gameCode=' + gameCode + '&gameName=' + gameName + '&serverCode=' + serverCode + '&serverName=' + serverName 
          + '&productGuid=' + productGuid + '&payMethod=' + payMehtod
          + '&fullName=' + fullName + '&characterName=' + characterName + '&email=' + email + '&country=' + encodeURI(country) + '&nonUsPhone=' + encodeURI(nonUsPhone) 
          + '&moneyType=' + moneyType ,
        type:'get',
        async:'false'
        });
}