var WS  = "http://"+document.location.host+"/get.php";
var WSP = "http://"+document.location.host+"/pl.php";
var WSPL = "http://"+document.location.host+"/pll.php";

function parseXML(xml /* req.responseXML */) {
	var obj = { _text : "" };
	var child = xml.firstChild;
	while (child) {
		if ((child.nodeName == "#text") || (child.nodeName =="#cdata-section")) {
			obj._text += child.nodeValue;
		} else if (child.nodeType == 1) {
			if (typeof obj[child.nodeName] == "undefined") {
				obj[child.nodeName] = [];
			}
			obj[child.nodeName][obj[child.nodeName].length] = parseXML(child);
		}
		child = child.nextSibling;
	}
	var att = xml.attributes;
	var i = 0;
	if (att) { // there are attributes
		for (var i = 0; i < att.length; i++) {
			obj[att[i].name] = att[i].value;
		}
	}
	if (obj._text.match(/^\s*$/)) {
		delete obj._text;
	}
	return obj;
}
// quickBuy's step 1
function buygold(o){location=o.parentNode.parentNode.cells[0].childNodes[0].href;}

window.addEvent('domready', function(){

   var xhr=new XHR({
    method:'get',
    onRequest:function(){
      $('games').options.length=0;
      $('games').options.add(new Option('Loading Game...',''));
    },
    onSuccess:function(/* {string} responesText} */txt,/* {Document} responseXML */xml){
      var jsonData = parseXML(xml); //parsing xhr.responseXML to json
      $('games').options.length=0;
      jsonData['games'][0]['game'].each(function(v,i){$('games').options.add(new Option(v._text,v.code))});
      $('gamename').value=jsonData['games'][0]['game'][0]._text;
      Cs();
      //addEvent some objs $game,$servers,$quantitys
      $('games').addEvent('change',Cs);
      $('servers').addEvent('change',Cq);
      $('quantitys').addEvent('change',Cp);

    },
    ansyc:false
    })

   //Add events of Elements in powerlevel's form

    if($('games1')){
     var pl=new PowerLevel();
	 $('games1').addEvent('change',function(){ pl.getlevel();})
     $('currentlevel').addEvent('change',function(){ pl.getpl();})
     $('desiredlevel').addEvent('change',function(){ pl.getpl();})
     }


   if($('games'))
   xhr.send(WS+"?action=game&code=");

   //LOAD FLASH  START
if($('tablink1')){
 if(typeof $('tablink1').onmouseover=='function')
   $('tablink1').onmouseover()
}

 var selServer = document.getElementById("selServer");
        var btnBuyGold = document.getElementById("btnBuyGold");
        if(selServer){
            selServer.onchange=function(){
                //location="buy_game_gold.php?code="+this.value+"&n="+this.options[this.selectedIndex].text;
            }
        }
        if(btnBuyGold){
            btnBuyGold.onclick=function(){
                location="buy_game_gold.php?code="+selServer.value+"&n="+selServer.options[selServer.selectedIndex].text;
            }
        }
   // FINISH FLASH

});

// quickBuy's step 2

var Cs=function(){
  /* summary: Load xml to set servers options
   * init:an initializer order number,_lg:an initializer function to set servers.options.length=0;
   * description:load the server_id xml to set $server options;
  */
      var xhr=new XHR({
	method:'get',
	onRequest:function(){
       var addZero=function(n){if(n.length!=2&&((n-0)<10)){return '0'+n}else{return n}}
  var d=new Date();
  $("OrderId").value=""+d.getFullYear()+addZero(d.getMonth()+1)+addZero(d.getDate())+addZero(d.getHours())+addZero(d.getMinutes())+addZero(d.getSeconds())+addZero(d.getMilliseconds());
	  $('servers').options.length=0;
          $('servers').options.add(new Option('Loading Game Server'));
	  $('gamename').value=$('games').options[$('games').selectedIndex].text;
	},
	onSuccess:function(/* {string} responesText} */txt,/* {Document} responseXML */xml){
	   var jsonData = parseXML(xml); //parsing xhr.responseXML to json
	   $('servers').options.length=0;
           jsonData['servers'][0]['server'].each(function(v,i){$('servers').options.add(new Option(v._text,v.code))});
           Cq($('servers').value);
	},
	ansyc:false
	})
      //do the send request
      xhr.send(WS+"?action=server&code="+$('games').value);
}
// quickBuy's step 3

var Cq=function(){
  var xhr=new XHR({
    method:'get',
    onRequest:function(){
      $('quantitys').options.length=0;
      $('quantitys').options.add(new Option('Loading'));
      $("servername").value=$('servers').options[$('servers').selectedIndex].text;
    },
    onSuccess:function(/* {string} responseText */txt, /* {Document} responseXML */ xml){
	
      $('quantitys').options.length=0;
      var jsonData = parseXML(xml); //parsing xhr.responseXML to json
      jsonData['prices'][0]['price'].each(function(v,i){
	$("unit_price").value = v.unit_price;
	var tmpOpt=new Option(v.qt,v._text);
	tmpOpt.setAttribute("discount",v.discount);
	tmpOpt.setAttribute("guid",v.guid);
	tmpOpt.setAttribute("number",v.number);
	$('quantitys').options.add(tmpOpt);
	delete tmpOpt;
	});
      Cp()
    },
    ansyc:false
    });
  xhr.send(WS+"?action=price&code="+$('servers').value);
}
// quickBuy's step 4
var Cp=function(){
  /* summary: set prices,discount,trade_num,item value;
   */
  var q;
  var price = $('quantitys').value;
  var showprice=function(p){
     var s = '$ '+p
         if(/^(101|201|6|16|17)/.test($('games').value)){
         var rateXHR =new XHR({
             method: 'get',
             async: false
             }).send('/rate.php');
         var rate = parseXML(rateXHR.transport.responseXML)
         for(var i=0;o=rate['currenciess'][0]['currencies'][i];i++){
             if(/(?:EUR|GBP)/i.test(o['code'][0]['_text']))
          s+='; '+o['symbol_left'][0]['_text']+''+(o['value'][0]['_text']*p).toFixed(2)+'';
         }

       }
     return s;
  }
  $('prices').value=showprice((Math.round((price*100)))/100); 

   if($('amount'))
  $('amount').value=(Math.round((price*100)))/100;
  q=$('quantitys').options[$('quantitys').selectedIndex];
  $('discount').value=q.getAttribute('discount');
  $('unit_price').value=q.getAttribute('guid');
  $('trade_num').value=q.getAttribute('number');
  $('item').value=q.text;
}


function checkpost(f){

   if(f.amount.value==""||f.amount.value==0){
	  alert('Please select Quantity');
	  return false;
    }
    if(/\W|^$/g.test(f.character_to.value)){
	  alert('Please input correct character name!');
          f.character_to.focus();
	  return false;
    }
    if(f.customer_full_name.value==""){
	  alert('Please input correct full name!');
          f.customer_full_name.focus();
	  return false;
    }
   var emailv=f.customer_email.value;
   if(!/^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/.test(emailv)){
    alert("Please Type correct email");
    f.customer_email.focus();
    return false;
    }

   if(f.customer_phone2.value=="" && (f.phone1.value.length !=3 || f.phone2.value.length !=3 || f.phone3.value.length!=4)){
	  alert('Please Type correct US /Non-US phone number. e.g xxx-xxx-xxxx');
      f.phone1.focus();
	  return false;
    }
	if(f.phone1.value.length =="")
   if((f.phone1.value.length ==0 && f.phone2.value.length == 0 && f.phone3.value.length == 0) && (f.customer_phone2.value.length<5 || f.customer_phone2.value.length>16)){
	  alert('Please type correct  Non-US phone number. e.g xxx-xxxxxxx');
      f.customer_phone2.focus();
	  return false;
    }
    var server = $('servers');
    if(/aegwynn/i.test(server.options[server.selectedIndex].text)){
     var r = window.confirm('Are you suce your server is '+server.options[server.selectedIndex].text+'?');
     if(r){
        return true;
     }else{
       return false;
     }
    }
    return true
}


 var PowerLevel=new Class({
     getpl:function(){
        var xhr=new XHR({
	    method:'get',
	    onSuccess:function(/* {string} responseText */txt,/* {Document} responseXML */xml){
		  
	     var Pr = /price=(\")([^\1]+)\1\s+time=\1([^\1]+)\1/i.exec(txt);
		 
      if(Pr){
		$('level_time').value=Pr[3];
		$('need_time').value=Pr[3].split("-")[1]-0+1;
		$('need_price').value=(Pr[2]-0).toFixed(2);
		$('gamename').value=$('games1').options[$('games1').selectedIndex].text;

		$('itemname').value=$('gamename').value+' '+$('currentlevel').value+'-'+$('desiredlevel').value+'';
	
      }
	    }
	   });
	  
	  xhr.send(WSPL+"?gamecode="+$('games1').value+'&startlevel='+$('currentlevel').value+'&endlevel='+$('desiredlevel').value);

	 },

     getlevel:function(){
	  var me=this;
	  var xhr=new XHR({
	    method:'get',

	    onSuccess:function(/* {string} responseText */txt,/* {Document} responseXML */xml){
		
	      var Pl = /End=(\")([^\1]+)\1\s+PLStart=\1([^\1]+)\1/i.exec(txt);
	      var c = $('currentlevel');
	      c.options.length = 0;
	      var e = $('desiredlevel');
	      e.options.length = 0;
		  
	      for(var i =1 ; i < Pl[2] ; i++){
		c.options.add(new Option(i,i));
			
	      }
	      for(var i = Pl[2] ;i >= Pl[3]-0; i--){			  
		e.options.add(new Option(i,i));
	      }
		  $('task').innerHTML='';
		  $('task').innerHTML=$('games1').options[$('games1').selectedIndex].text;
		 
              me.getpl();
	    }
	   });
	  xhr.send(WSP+"?action=level&game="+$('games1').value);
	 }

      })

