
var xhr = null;
var aStatus = [];
var cMbxUrl = "http://" + window.location.hostname; 

var cAppName = "";
// var nMainW = parent.document.getElementById("adsp_mbx").scrollWidth;

GetAppName();

function GetAppName()
{
	var ua = navigator.userAgent.toLowerCase();
	if(ua.indexOf("opera") != -1) 
		cAppName = "opera";
	else if(ua.indexOf("msie") != -1) 
		cAppName = "msie";
	else if(ua.indexOf("safari") != -1)
		cAppName = "safari";
	else if(ua.indexOf("mozilla") != -1) 
	{
		if(ua.indexOf("firefox") != -1) 
			cAppName = "firefox";
		else
			cAppName = "mozilla";
	}
}

function CheckData(nType)
{	
	var cName, cRef;
	switch(nType)
	{
		case 1:
			cName = "game_id";
			cRef = "game";
			break;
		case 2:
			cName = "server_id";
			cRef = "server";
			break;
		case 3:
			cName = "faction_id";
			cRef = "faction";
			break;
		case 4:
			cName = "currency_amount";
			cRef = "amount";
			break;
		case 5:
			cName = "currency";
			cRef = "currency_rate";
			break;
		default:
			return false;
	}		
		
	if(SearchStatus(cName + "_st") != -1) ClearStatus(cName + "_st");		
	
	var selCtrl = document.getElementById(cName);
	if(selCtrl && selCtrl.value > 0){
		document.getElementById("act").value = cRef;		
		TriggerReq(nType);			
	}	
}

function TriggerReq(nType)
{
	if(SearchStatus("prc_st") != -1) ClearStatus("prc_st");
	if(CreateXHR()){
		//var oImgLoader = document.getElementById("loading");
		//oImgLoader.style.display = "";
		var g_id = document.getElementById("game_id").value;
		var s_id = document.getElementById("server_id").value;
		var f_id = document.getElementById("faction_id").value;		
		
		var amt_ctrl = document.getElementById("currency_amount");
		var cur = document.getElementById("currency").value;
		var amt = (amt_ctrl.options.length == 0)?"0":amt_ctrl.value;
		var act = document.getElementById("act").value;
		var param = "game_id="+g_id+"&server_id="+s_id+"&faction_id="+f_id+"&amt="+amt+"&cur="+cur+"&act="+act;	
		
		xhr.open("POST", cMbxUrl+"/linked/get_pricedata.php", true);
		xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
		xhr.onreadystatechange = function()
		{
			if(xhr.readyState == 4) 
			{
				if(xhr.status == 200)
				{
					try
					{
						HandleResponse();
					}
					catch(e)
					{
						alert("Error reading response. " + e.toString());
					}
				}
				else
				{
					alert("Error retreiving the data. " + xhr.statusText);
				}
			}
		}
		
		// Disp prog status
		if(nType == 1)
			var aSt = ["server_id","faction_id","currency_amount","prc"];
		else
			var aSt = ["prc"];
		for(var i in aSt) SetStatus(aSt[i]);
		xhr.send(param);
	}
	else alert("Error: cannot create xhr.");
}

function CreateXHR()
{
	if(xhr == null)
	{
		if(window.XMLHttpRequest)
			xhr = new XMLHttpRequest();
		else if(window.ActiveXObject)
			xhr = new ActiveXObject("Microsoft.XMLHTTP");
		else
			throw new Error("Program cound not create XHR object.");
	}					
	return (xhr != null);
}

function getServerListForGame(game_id) {
	
	var q_buy = document.getElementById("quick-buy");
	$.post('/linked/get_server_list.php', {game_id:game_id}, function(data) {
  		$('#quick-buy').html(data);
	});
}

function HandleResponse()
{
	var cRaw = xhr.responseText;		
	//alert("return text: "+cRaw);
	var oData = cRaw.parseJSON();
	document.getElementById("act").value = "";
	
	var isFrontPage = document.getElementById("isFrontPage").value;
	
	if(oData["s_status"] && oData["f_status"] && oData["amt_status"] && oData["cur_status"] && oData["price_status"])
	{	
		var s_sel = document.getElementById("server_id");
		var f_sel = document.getElementById("faction_id");
		var amt_sel = document.getElementById("currency_amount");
		var cur_sel = document.getElementById("currency");
		var dt_list = document.getElementById("data_list");
		var dt_list_t = document.getElementById("data_list_trust");
		
		if((oData["s_status"] == "renew") && oData["s_keys"] && (oData["s_keys"].length == 0))
		{ 
			oData["s_status"] = "blank";
		}
		if((oData["f_status"] == "renew") && oData["f_keys"] && (oData["f_keys"].length == 0))
		{ 
			oData["f_status"] = "blank";
		}
		if((oData["price_status"] == "renew") && oData["price_data"] && (oData['price_data'].length == 0))
		{ 
			oData["price_status"] = "no_data";
		}
		if((oData["price_status_t"] == "renew") && oData["price_data_t"] && (oData['price_data_t'].length == 0))
		{ 
			oData["price_status_t"] = "no_data";
		}

		switch(oData["s_status"])
		{
			case "blank": 
			default:
				ClearList(s_sel);
				s_sel.disabled = true;
				break;
			case "same":
				break;
			case "renew":
				ClearList(s_sel);				
				if(oData["s_keys"].length > 0)
				{				
					s_sel.disabled = false;	
					for(var i=0; i<oData["s_keys"].length; i++)
					{
						var oOption = document.createElement('option');
						oOption.text = oData["s_values"][i];
						oOption.value = oData["s_keys"][i];
						try {
							s_sel.add(oOption, null); // standards compliant; doesn't work in IE
						}
						catch(ex) {
							s_sel.add(oOption); // IE only
						}
					}
					if(oData["s_keys"].length == 1)
						s_sel.selectedIndex = 1;
					else
						s_sel.selectedIndex = 0;
				}				
				else s_sel.disabled = true;								
		}

		switch(oData["f_status"])
		{
			case "blank": 
			default:
				ClearList(f_sel);
				f_sel.disabled = true;
				break;
			case "same":
				break;
			case "renew":
				ClearList(f_sel);				
				if(oData["f_keys"].length > 0)
				{				
					f_sel.disabled = false;	
					for(var i=0; i<oData["f_keys"].length; i++)
					{
						var oOption = document.createElement('option');
						oOption.text = oData["f_values"][i];
						oOption.value = oData["f_keys"][i];
						try {
							f_sel.add(oOption, null); // standards compliant; doesn't work in IE
						}
						catch(ex) {
							f_sel.add(oOption); // IE only
						}
					}
					if(oData["f_keys"].length == 1)
						f_sel.selectedIndex = 1;
					else
						f_sel.selectedIndex = 0;
				}				
				else f_sel.disabled = true;		
		}

		switch(oData["amt_status"])
		{
			case "blank": 
			default:
				ClearList(amt_sel);
				//amt_sel.disabled = true;
				break;
			case "same":
				break;
			case "renew":			
				ClearList(amt_sel);
				nIdx = oData["amt_sel_idx"];
				if((typeof nIdx != undefined) && oData["amt_values"].length > 0)
				{					
					amt_sel.disabled = false;
					for(var i=0; i<oData["amt_values"].length; i++)
					{
						var oOption = document.createElement('option');
						oOption.text = oData["amt_values"][i];
						oOption.value = i + 1;
						try {
							amt_sel.add(oOption, null); 
						}
						catch(ex) {
							amt_sel.add(oOption); 
						}
					}
					amt_sel.selectedIndex = nIdx + 1; // plus offset 
				}	
				else
				{ 
					amt_sel.selectedIndex = 0;			
					amt_sel.disabled = true;
				}
		}	
		try
		{
			if(cAppName != "msie")
				dt_list.innerHTML = "";
			else
				ClearOldData();
		}
		catch(e)
		{
			alert("EEEE1 : " + e.toString());
		}	
		switch(oData["cur_status"])
		{
			case "blank": 
			default:
				ClearList(cur_sel);
				amt_sel.disabled = true;
				break;
			case "same":
				break;
			case "renew":			
				ClearList(cur_sel);
		}	

		switch(oData["price_status"])
		{
			case "no_data":
				SetTableMargin(2);
				LoadEmptyBox(1);
				break;			
			case "renew":
				var oTR, oTD, col1, col2, col3, col4, col5;
				for(var i=0; i<oData['price_data'].length; i++)
				{
					col1 = oData['price_data'][i]["col1"];
					col2 = oData['price_data'][i]["col2"];
					col3 = oData['price_data'][i]["col3"];
					col4 = oData['price_data'][i]["col4"];
					col5 = oData['price_data'][i]["col5"];
					if(cAppName != "msie")
					{
						dt_list.innerHTML += '';
						if(isFrontPage != '1') {
						
							dt_list.innerHTML += '<tr valign="top"><td style="width: 100px;">' + col1 + '</td><td style="text-align: right; width: 100px;">' + col2 + '</td><td style="text-align: center; width: 80px; font-weight: bold;">' + col3 + '</td><td style="width: 120px;">' + col4 + '</td><td style="text-align: center; width: 80px;">' + col5 + '</td></tr>';
							
						} else {
						
							dt_list.innerHTML += '<tr valign="top"><td style="text-align: right; width: 100px;">' + col2 + '</td><td style="text-align: center; width: 80px; font-weight: bold;">' + col3 + '</td><td style="width: 120px;">' + col4 + '</td><td style="text-align: center; width: 80px;">' + col5 + '</td></tr>';
						}
					}
					else
					{
						oTR = dt_list.insertRow();
						if(oTR)
						{
							if(isFrontPage != '1') {
							
								oTD = oTR.insertCell();	
								oTD.style.verticalAlign = "top";
								oTD.style.width = "81px";
								oTD.innerHTML = col1;
							}
							
							oTD = oTR.insertCell();	
							oTD.style.textAlign = "right";
							oTD.style.verticalAlign = "top";
							oTD.style.width = "81px";
							oTD.innerHTML = col2;
							
							oTD = oTR.insertCell();	
							oTD.style.textAlign = "center";
							oTD.style.verticalAlign = "top";
							oTD.innerHTML = col3;

							oTD = oTR.insertCell();	
							oTD.style.verticalAlign = "top";
							oTD.style.width = "81px";
							oTD.innerHTML = col4;
							
							oTD = oTR.insertCell();	
							oTD.style.textAlign = "center";
							oTD.style.verticalAlign = "top";
							oTD.innerHTML = col5;
						}
					}
				}
				SetTableMargin(2);
				break;
			case "blank":
			default:
				SetTableMargin(1);
				LoadEmptyBox();
				break;
		}
		switch(oData["price_status_t"])
		{
			case "no_data":
				SetTableMargin_Trust(1);
				//LoadEmptyBox(1);
				break;			
			case "renew":
				var oTR, oTD, col1, col2, col3, col4, col5;
				//dt_list_t.innerHTML = '';
				if(cAppName != "msie")
					dt_list_t.innerHTML = "";
				else
					ClearOldData1()
				for(var i=0; i<oData['price_data_t'].length; i++)
				{
					col1 = oData['price_data_t'][i]["col1"];
					col2 = oData['price_data_t'][i]["col2"];
					col3 = oData['price_data_t'][i]["col3"];
					col4 = oData['price_data_t'][i]["col4"];
					col5 = oData['price_data_t'][i]["col5"];
					if(cAppName != "msie")
					{
						dt_list_t.innerHTML += '';
						
						if(isFrontPage != '1') {
						
							dt_list_t.innerHTML += '<tr valign="top"><td style="width: 100px;">' + col1 + '</td><td style="text-align: right; width: 100px;">' + col2 + '</td><td style="text-align: center; width: 80px; font-weight: bold;">' + col3 + '</td><td style="width: 120px;">' + col4 + '</td><td style="text-align: center; width: 80px;">' + col5 + '</td></tr>';
							
						} else {
						
							dt_list_t.innerHTML += '<tr valign="top"><td style="text-align: right; width: 100px;">' + col2 + '</td><td style="text-align: center; width: 80px; font-weight: bold;">' + col3 + '</td><td style="width: 120px;">' + col4 + '</td><td style="text-align: center; width: 80px;">' + col5 + '</td></tr>';
						}
					}
					else
					{
						oTR = dt_list_t.insertRow();
						if(oTR)
						{
							if(isFrontPage != '1') {
							
								oTD = oTR.insertCell();	
								oTD.style.verticalAlign = "top";
								oTD.style.width = "81px";
								oTD.innerHTML = col1;
							}
						
							oTD = oTR.insertCell();	
							oTD.style.textAlign = "right";
							oTD.style.verticalAlign = "top";
							oTD.style.width = "81px";
							oTD.innerHTML = col2;
						
							oTD = oTR.insertCell();	
							oTD.style.textAlign = "center";
							oTD.style.verticalAlign = "top";
							oTD.innerHTML = col3;

							oTD = oTR.insertCell();	
							oTD.style.verticalAlign = "top";
							oTD.style.width = "81px";
							oTD.innerHTML = col4;
						
							oTD = oTR.insertCell();	
							oTD.style.textAlign = "center";
							oTD.style.verticalAlign = "top";
							oTD.innerHTML = col5;
						}
					}
				}
				SetTableMargin_Trust(2);
				break;
			case "blank":
			default:
				SetTableMargin_Trust(1);
				LoadEmptyBox();
				break;
		}
		ClearAllStatus();						
	}
	else
	{
		SetTableMargin(1);
		SetTableMargin_Trust(1);
		LoadEmptyBox();
		ClearList(s_sel);	
		ClearList(amt_sel);
		ClearAllStatus();
		if(cAppName != "msie")
			dt_list.innerHTML = "";
		else
			ClearOldData();
	}
	//var oImgLoader = document.getElementById("loading");
	//oImgLoader.style.display = "none";
}

function SetStatus(cCtrlRef)
{		
	var ctrl = document.getElementById(cCtrlRef);
	if(ctrl)
	{		
		//alert("status"+ctrl.value);
		//ctrl.disabled = true;
		var cpos = GetElementAbsolutePos(ctrl);
		var main = document.getElementById("search_form");
		var prg = document.getElementById("prg");
		var obj = prg.cloneNode(true);	
		main.appendChild(obj);	
		
		obj.id = cCtrlRef + "_st";		
		obj.style.display = "";
				
		if(cCtrlRef != "prc")
		{
			obj.style.top = cpos.y + 2; 
			obj.style.left = cpos.x + 10;
		}
		else
		{
			var dt_list = document.getElementById("data_list");

			if(cAppName != "msie")
				dt_list.innerHTML = '<tr><td colspan="3" style="height:35px;"></td></tr>';
			else
			{
				ClearOldData();
				var oTR = dt_list.insertRow();
				if(oTR)
				{
					var oTD = oTR.insertCell();
					oTD.colSpan = 3;
					oTD.style.height = "35px";
				}
			}
								
			obj.style.padding = 4;
			obj.style.top = cpos.y + 35;
			obj.style.left = cpos.x + 90;			
		}
					
		if(SearchStatus(obj.id) == -1)
		{
			aStatus[aStatus.length] = obj.id;
		}
	}
}

function ClearOldData()
{
	for(var i=document.getElementById("data_list").rows.length - 1; i>=0; i--)
	{
		document.getElementById("data_list").deleteRow(i);
	}
}

function ClearOldData1()
{
	for(var i=document.getElementById("data_list_trust").rows.length - 1; i>=0; i--)
	{
		document.getElementById("data_list_trust").deleteRow(i);
	}
}

function ClearAllStatus()
{
	if(aStatus.length > 0)
	{	
		var num = aStatus.length;
		if(num > 0)
		{
			for(var i=num - 1; i>=0; i--) ClearStatus(aStatus[i]);
		}
	}
}

function ClearStatus(cCtrlRef)
{
	if(cCtrlRef)
	{
		var ctrl = document.getElementById(cCtrlRef);		
		var main = document.getElementById("search_form");
		var selCtrl = document.getElementById(cCtrlRef.substr(0, cCtrlRef.length - 3));
		if(ctrl && main && selCtrl)
		{
		//	selCtrl.disabled = false;
			main.removeChild(ctrl);
			var idx = SearchStatus(cCtrlRef);
			if(idx >= 0) aStatus.splice(idx, 1);		
		}
	}
}

function SearchStatus(str)
{
	if(str && (aStatus.length > 0))
	{
		for(var i in aStatus)
		{
			if(aStatus[i].toLowerCase() == str.toLowerCase()) return i;
		}		
	}
	return -1;
}	

function SetTableMargin(nType)
{
	var regexp = /[1-2]/
	if(regexp.exec(nType) == null) nType = 1;
	
	var oData = document.getElementById("prices");
	var oHeading = document.getElementById("head_prices");
	if(nType == 1)
	{
		oData.style.display = "none";
		oHeading.style.display = "none";
	}
	else
	{		
		oData.style.display = "";
		oHeading.style.display = "";
	}
}

function SetTableMargin_Trust(nType)
{
	var regexp = /[1-2]/
	if(regexp.exec(nType) == null) nType = 1;
	
	var oData = document.getElementById("prices_trust");
	var oHeading = document.getElementById("head_prices_trust");
	if(nType == 1)
	{		
		oData.style.display = "none";
		oHeading.style.display = "none";
	}
	else
	{		
		oData.style.display = "";
		oHeading.style.display = "";
	}
}


function LoadEmptyBox(isDataEmpty)
{
	var dt_list = document.getElementById("data_list");
	if(dt_list)
	{
		var emPreTag = '<span style="font-weight:bold;font-style:italic;">';
		if(isDataEmpty == undefined)
			var msg = 'Please first select your ' + emPreTag + 'game, server</span> and ' + emPreTag + 'amount.</span>';
		else 
			var msg = '<span style="color:red; font-weight:bold; font-style:italic;">No prices found for this selection.</span>  Please check <a class="blacklink" href="' + cMbxUrl + '" target="_blank">mmobux.com</a> again';					
		
		if(cAppName != "msie")
		{	
			dt_list.innerHTML = '<tr><td colspan="5" style="border-left:1px solid #636363;border-right:1px solid #636363;color:#333;text-align:center;vertical-align:center;height:62px;">' + msg + '</td></tr>';
		}
		else
		{
			var oTR = dt_list.insertRow();
			if(oTR)
			{
				var oTD = oTR.insertCell();
				oTD.colSpan = 5;
				oTD.style.textAlign = "center";
				oTD.style.verticalAlign = "middle";
				oTD.style.color = "#333333";
				oTD.style.borderLeft = "1px solid #636363";
				oTD.style.borderRight = "1px solid #636363";
				oTD.style.height = "62px";
				oTD.innerHTML = msg; 
			}
		}
	}
}

function ClearList(obj)
{
	if(obj && (obj.type == "select-one"))
	{		
		var nTotal = obj.options.length;
		for(var i=nTotal; i>=1; i--) obj.remove(i);		
		return true;
	}
	return false;
}

var __isFireFox = navigator.userAgent.match(/gecko/i);

function GetElementAbsolutePos(element) 
{  
	var res = new Object();  
	res.x = 0; res.y = 0;  
	if (element !== null) 
	{  
		res.x = element.offsetLeft;   
		res.y = element.offsetTop;   
   
		var offsetParent = element.offsetParent;  
		var parentNode = element.parentNode;  

		while (offsetParent !== null) 
		{  
			res.x += offsetParent.offsetLeft;  
			res.y += offsetParent.offsetTop;  

			if (offsetParent != document.body && offsetParent != document.documentElement) 
			{			  
				res.x -= offsetParent.scrollLeft;  
				res.y -= offsetParent.scrollTop;  
			}  
			//next lines are necessary to support FireFox problem with offsetParent  
			if (__isFireFox) 
			{  
				while (offsetParent != parentNode && parentNode !== null) 
				{  
					res.x -= parentNode.scrollLeft;  
					res.y -= parentNode.scrollTop;  
  
					parentNode = parentNode.parentNode;  
				}      
			}  
			parentNode = offsetParent.parentNode;  
			offsetParent = offsetParent.offsetParent;  
		}  
	}  
	return res;  
}  

(function (s) 
{
  // Augment String.prototype. We do this in an immediate anonymous function to
  // avoid defining global variables.

  // m is a table of character substitutions.

  var m = {
    '\b': '\\b',
    '\t': '\\t',
    '\n': '\\n',
    '\f': '\\f',
    '\r': '\\r',
    '"' : '\\"',
    '\\': '\\\\'
  };

  s.parseJSON = function (filter) 
  {
    // Parsing happens in three stages. In the first stage, we run the text against
    // a regular expression which looks for non-JSON characters. We are especially
    // concerned with '()' and 'new' because they can cause invocation, and '='
    // because it can cause mutation. But just to be safe, we will reject all
    // unexpected characters.

    try {
      if (/^("(\\.|[^"\\\n\r])*?"|[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t])+?$/.
        test(this)) {

          // In the second stage we use the eval function to compile the text into a
          // JavaScript structure. The '{' operator is subject to a syntactic ambiguity
          // in JavaScript: it can begin a block or an object literal. We wrap the text
          // in parens to eliminate the ambiguity.

          var j = eval('(' + this + ')');

          // In the optional third stage, we recursively walk the new structure, passing
          // each name/value pair to a filter function for possible transformation.

          if (typeof filter === 'function') {

            function walk(k, v) {
              if (v && typeof v === 'object') {
                for (var i in v) {
                  if (v.hasOwnProperty(i)) {
                    v[i] = walk(i, v[i]);
                  }
                }
              }
              return filter(k, v);
            }

            j = walk('', j);
          }
          return j;
        }
      } catch (e) {

      // Fall through if the regexp test fails.

      }
      throw new SyntaxError("parseJSON");
    };
  }
) (String.prototype);


