/*
    This file is part of BBoM Usage.
    Copyright (C) <2008>  <Terence Ang>

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

var mobileNo, icNo;
var BBOMUsage = 0;
var BBOMunit = "MB";
var BBOMasof,BBOMcycle;
var currentWidth = 0;
var is_setting = false;
var dataSet = false;
var scrLength = 280;
var targetDevice = true;

// the http object
var http = new XMLHttpRequest();

function load()
{
	// check for iPhone or iPhone touch
	var agent=navigator.userAgent.toLowerCase();
	var is_iphone = (agent.indexOf('iphone') != -1);
	var is_ipod = (agent.indexOf('ipod') != -1);
	targetDevice = (is_iphone || is_ipod);

restoreSetting();

if (localStorage.getItem('dataSet'))
	{
		getBBOMData();
		updateIndicator()
	}
	else
	{
		is_setting = true;
	}
	
CheckOrientation();
document.getElementById("content").style.display = "block";
showSetting(is_setting);

}

function restoreSetting(){
	//get data from local storage
	data_set = localStorage.getItem('dataSet') ? localStorage.getItem('dataSet') : false;
	is_setting = !data_set; //if data not set show bottom panel.
	
	//reset textfield
	document.getElementById("ansText1").textContent = "Enter your Data SIM and IC number";
	document.getElementById("ansText2").textContent = "Click update to save setting";
	document.getElementById("ansText3").textContent = "";
	//restore text field in input
	document.getElementById("mobileInput").value = localStorage.getItem('mobileData') ? localStorage.getItem('mobileData') : "65";
	document.getElementById("icInput").value = localStorage.getItem('icData') ? localStorage.getItem('icData') : "S";
	document.getElementById("limitInput").value = localStorage.getItem('limitData') ? localStorage.getItem('limitData') : "50000";
	document.getElementById("mobileText").textContent = localStorage.getItem('mobileData') ? localStorage.getItem('mobileData') : "--------";
	
	document.getElementById("content").style.display = "block";
	document.getElementById("top_panel").style.marginTop = (is_setting)?'36px':'90px';
	document.getElementById("footer").style.marginTop = (is_setting)?'5px':'0px';
	showSetting(is_setting);
}

// save the settings from form to localdata
function saveSettings(){
// is form blank?
	
	if ((document.getElementById("limitInput").value == 0) || document.getElementById("icInput").value == 'S' || document.getElementById("mobileInput").value == '65') return;
	if (document.getElementById("mobileInput").value.length != 10)
	{
		document.getElementById("ansText3").textContent = "Mobile no. must be 10 digit";
		return;
	};
	
	if (!(document.getElementById("icInput").value.length == 9 || document.getElementById("icInput").value.length == 10))
	{
		document.getElementById("ansText3").textContent = "ID No. must be 9 or 10 digit";
		return;
	};
document.getElementById("mobileText").textContent = document.getElementById("mobileInput").value;
	
//update cookies	
	localStorage.setItem('mobileData', document.getElementById("mobileInput").value);
    localStorage.setItem('icData', document.getElementById("icInput").value);
    localStorage.setItem('limitData', document.getElementById("limitInput").value);
	localStorage.setItem('dataSet', true);
	setTimeout(function() { window.scrollTo(0, 1) }, 100)
	toggleSetting()
    getBBOMData();
	
}

function getBBOMData()
{

	if (navigator.onLine)
		{
		document.getElementById("ansText1").textContent = "Fetching Data";
		document.getElementById("ansText2").textContent = "Contacting Server";
		document.getElementById("ansText3").textContent = "Please Wait";
	   	var BBOMUrl = "scripts/getdata.php";
      	http.onload = function(e) {httpResponse(http);}
		http.open("GET", BBOMUrl+'?mobileData='+document.getElementById("mobileInput").value+'&icData='+document.getElementById("icInput").value,true);
		http.send(null);
	}
	else
	{
		alert("you are offline, no update will be performed");
	}
}

// read the response from the HTTP Request object
function httpResponse(http)
{
	if (http.responseText == ""){
		document.getElementById("anstext1").textContent = "Error fetching DATA. <a href='getBBOMData()'>Try Again</a>";
		return;
	}
	if (http.readyState == 4)
		parseHttp(http.responseText);
}

function parseHttp(httptext){
	

//check for error        
     if (httptext  == "Server Update"){
		document.getElementById("ansText1").textContent = "Singtel protocol Change";
        document.getElementById("ansText2").textContent = "Please check later!";

    return
		}
    if (httptext  == "bad data"){
		document.getElementById("ansText1").textContent = "Error reading BBOM data.";
        document.getElementById("ansText2").textContent = "Are your login details correct?";
    return
        }
     if (httptext  == "server not found"){
		document.getElementById("ansText1").textContent = "Server busy or not found.";
        document.getElementById("ansText2").textContent = "Are your login details correct?";

    return
        }

//split results from php
var returntext = httptext.split(";");
        
     BBOMUsage = returntext[2];
     BBOMunit = returntext[3];
     BBOMasof = returntext[4];
     BBOMcycle = returntext[1]; 

	if (document.getElementById("limitInput").value < 1000) {
	document.getElementById("ansText1").textContent = BBOMUsage + " " + BBOMunit +" of " + document.getElementById("limitInput").value +" MB";
	document.getElementById("ansText2").textContent = "as of "+ BBOMasof + "Hrs";
							}
	else 
							{
	document.getElementById("ansText1").textContent = BBOMUsage + " " + BBOMunit +" of " + (document.getElementById("limitInput").value /1000) +" GB";
	document.getElementById("ansText2").textContent = "as of "+ BBOMasof + " hrs";
							}

	document.getElementById("ansText3").textContent = "Cycle Date is on " + BBOMcycle;

	updateIndicator(); 	   

}

function mailme(event)
{
	var myRef = window.open('http://iphone.sgapps.com','mywin','toolbar=yes,location=yes,directories=yes,status=yes,menubar=yes,scrollbars=yes,copyhistory=yes, resizable=yes');
}


function CheckOrientation(){
		if (!targetDevice){
		document.body.setAttribute("class", "portrait");  
		return;
		}
		updateOrientation();
}

function updateOrientation()
{
	var orientation = window.orientation;
//		var orientation = 90;
  	switch(orientation)
  	{
    case 0:      
		document.getElementById("top_panel").style.marginTop = (is_setting)?'36px':'90px';
		document.getElementById("footer").style.marginTop = (is_setting)?'5px':'0px';
		document.body.setAttribute("class", "portrait"); 
		showSetting(is_setting);
		scrLength = 280;
		updateIndicator();
        break;  
 
    case 90:
		showSetting(false); 
		document.getElementById("top_panel").style.marginTop ='50px';    
		document.body.setAttribute("class", "landscape");  
		scrLength = 400;
		updateIndicator();
        break;
 
    case -90:  
		showSetting(false);
		document.getElementById("top_panel").style.marginTop ='50px';
		document.body.setAttribute("class", "landscape");  
		scrLength = 400;    
		updateIndicator();
        break;
  }
  
}

function updateIndicator(){

	var BBOMUsageTemp = (BBOMunit == "GB")?BBOMUsage * 1000:BBOMUsage;
	var indicator1 = document.getElementById("BBOMIndicator");
	createIndicator(indicator1,BBOMUsageTemp,0,document.getElementById("limitInput").value,scrLength);
}

function toggleSetting()
	{
		is_setting = !is_setting;

		document.getElementById("top_panel").style.marginTop = (is_setting)?'36px':'90px';
		document.getElementById("footer").style.marginTop = (is_setting)?'5px':'0px';
		showSetting(is_setting);
}

function showSetting(show)
	{   

		document.getElementById("bottom_panel").style.display = (show)?'block':'none';
}


function indicatorSetup(track)
{
	createIndicator(track,0,0,100,scrLength); 
}

function createIndicator(track,currentValue,minValue,maxValue,length){
//var length = track.offsetWidth;
var imageWidth = 12;
var spacing = 0;
var numofCell = parseInt(length /(spacing + imageWidth));
var criticalValue = parseInt(.9 * numofCell);
var warningValue = parseInt(.7 * numofCell);
var onValue = ((currentValue - minValue) / (maxValue-minValue))*numofCell;
onValue = (onValue > 0 && onValue <1 )?1:onValue;
var delta = 0;
var imagesel="";

//cleanup
var cellHolder = document.getElementById("cellHolder");
if (cellHolder != null) {
	cellHolder.parentNode.removeChild(cellHolder);
}

cellHolder = document.createElement("div");
cellHolder.setAttribute("id", "cellHolder")
cellHolder.style.position = "absolute";
cellHolder.style.display = "block";
cellHolder.style.top = "0px";
cellHolder.style.width = length;
cellHolder.style.height = "30px";
track = track.appendChild(cellHolder);

track = document.getElementById("cellHolder");

var i;
for (i=0;i<numofCell;i=i+1) 
{
	delta = i * (imageWidth + spacing);
	var element = document.createElement("div");
	var style = element.style;
	style.position = "absolute";
	style.display = "block";
	style.top = "0px";
	style.left = delta + "px";
	style.width = imageWidth + "px";
	style.height = "30px"; 
	if (i >= onValue)
		imagesel="Off";
	else if (i >= criticalValue)
		imagesel="Critical";
	else if (i >= warningValue)
		imagesel="Warning";
	else if (i <= onValue)
		imagesel="On";
	style.background = "url(Images/indicator"+imagesel+".png) no-repeat top left";
	track.appendChild(element);
}

}