//#### Helper Functions ####
function h2d(h) {return parseInt(h,16);}
function b2d(b) {return parseInt(b,2);}
function d2b(d) {return Array(9 - parseInt(d,10).toString(2).length).join("0") + parseInt(d,10).toString(2);}
function d2h(d) {return parseInt(d,10).toString(16);}
function d2oct(d) {return parseInt(d,10).toString(8);}

//#### IP Encoding Conversion Functions ####
function ip2d(ip){
 var newip = "";
 ipchunk = ip.split(".");
 for(i = 0; i < ipchunk.length; i++){
 	 newip += "" + d2b(ipchunk[i]);
 }
 return b2d(newip);
}

function ip2h(ip){
 ip = ip2d(ip);
 return "0x" + d2h(ip);
}

function ip2oct(ip){
 var newip = "";
 ipchunk = ip.split(".");
 for(i = 0; i < ipchunk.length; i++){
 	if(ipchunk[i] == 0){ newip += "0"; }
 	else { newip += "0" + d2oct(ipchunk[i]); }
 	if(i < 3) { newip += "."; }
 }
 return newip;
}

function ip2hdot(ip){
 var newip = "";
 ipchunk = ip.split(".");
 for(i = 0; i < ipchunk.length; i++){
 	if(ipchunk[i] == 0){ newip += "0"; }
 	else { newip += "0x" + d2h(ipchunk[i]); }
 	if(i < 3) { newip += "."; }
 }
 return newip;
}

function GetE( elementId ){
    return document.getElementById( elementId ) ; }

function UpdateRealtimeURL(){
 sValue = GetE("divRealtimeURL").innerHTML;

 var sIP = GetE("ip").value;
 var sIPEncoding = GetE("IPEncoding").options[GetE("IPEncoding").selectedIndex].value;

 if(sIPEncoding == "Decimal"){
 	sIP = ip2d(sIP);
 } else if(sIPEncoding == "Hex") {
	sIP = ip2h(sIP);
 } else if(sIPEncoding == "Octal") {
	sIP = ip2oct(sIP);
 } else if(sIPEncoding == "Hex with Dot") {
	sIP = ip2hdot(sIP);
 }

 sValue = "http://" + sIP;
 GetE("divRealtimeURL").innerHTML = "Encoded IP: <a href='" + sValue + "' target='_blank'>" + sValue + "</a>";
}



//#### Prepopulate the Blog Post box with an IP ####
if(GetE("ip").value.length < 6)
	GetE("ip").value = "64.233.169.104";
UpdateRealtimeURL();

