_longitude =  geoip_longitude();
_latitude = geoip_latitude();
_cityCountry = geoip_city()+", "+geoip_country_name();
/*_Day = null;
_Date = null;
_Month = null;
_Year = null;
_Hour = null;
_Minute= null;*/
_GMT = null;
_CurrentUnixTime=null;
_currentTime = null;
_xmldata =null;
_when = "today"; //tomorrow, 7days
_today = null; //save the date for later use
_tomorrow = null;
_next7days = null;
_tried = 0; //how many times should it forecast query before give up

$(document).ready(function() {

    $('#search_btn').click(function(){
        Search.city();
        return false;
    });


    /*
    TODO
    Need to make a function here, dup codes
     */
    $('#forecast_tomorrow').click(function(){
        if(_when != "tomorrow")
        {
            _when = "tomorrow";
            Forecast.weather();
            Helper.changeCityHead();
        }
        return false;
    });
    $('#forecast_today').click(function(){
        if(_when != "today")
        {
            _when = "today";
            Forecast.weather();
            Helper.changeCityHead();
        }
        return false;
    });
    $('#forecast_7days').click(function(){
        if(_when != "next7days")
        {
            _when = "next7days";
            Forecast.weather();
            Helper.changeCityHead();
        }
        return false;
    });

 

    //IMPORTANT
    /**
     * Localtime.getTime IS the gateway before it heads to FORECAST
     * DO NOT CALL THIS UNLESS YOU HAVE INFO: >>> LONGITUDE AND LATITUDE <<<
     */

    //STEP 1
    /**                 DEFAULT
     * After we have retrieve the lat, long position
     * then we send them to Localtime obj
     */
    Localtime.getTime();

    //STEP 2
    /**
     * When the Localtime got the answer and witht time, GMT etc
     * We will go to next step in complete function
     */
});

Localtime ={
    getTime:function()
    {
        //AJAX to be sur to use success and complete function
        $.ajax({
            type: "GET",
            url: "http://ws.geonames.org/timezoneJSON?lat="+_latitude+"&lng="+_longitude+"&callback=?",
            dataType: "json",
            success: function(data) {
                if(data.status != "12")
                {
                    var currentTime = data.time.toString().replace(/\-/g, "/");

                    //From 2010-03-23 15:10 -> "Tue, 12 Jan 2010 20:15:04 +0700"
                    _currentTime = new Date(currentTime);

                    //save this for xml filter
                    _CurrentUnixTime = data.time.toString();

                    /*
                    //..after splitted ["Tue,", "12", "Jan", "2010", "20:15:04", "+0700"]
                    var datetimeArray = _currentTime.toString().split(" ");
                    _Day = datetimeArray[0];
                    _Date = datetimeArray[1];
                    _Month = datetimeArray[2];
                    _Year = datetimeArray[3];*/
                    _GMT = data.gmtOffset;

                    Localtime.forecastDateOptions();
                }
                else{
                    alert("Not again, the Geonames.org is down...")
                }
            },
            complete:function (data) {

                //STEP 2 : A
                /**
                 * We now proceed to next step. We call YR.no for XML
                 * MAKE SURE YOU HAVE LONG,LAT INFO
                 * ------------------------------------
                 */
                Forecast.weather();
            }
        });
    },

    /**
     * Edit the date buttons on index site
     */
    forecastDateOptions:function(){

        var today = new Date(_currentTime);
        _today = Localtime.convertDay(today.getDay())+", ngày "+today.getDate()+" "+Localtime.convertMonth(today.getMonth());
        $("#forecast_today").attr("title",_today);

        _tomorrow = new Date(today.setDate(today.getDate()+1));
        _tomorrow = Localtime.convertDay(_tomorrow.getDay())+", ngày "+_tomorrow.getDate()+" "+Localtime.convertMonth(_tomorrow.getMonth());
        $("#forecast_tomorrow").attr("title",_tomorrow);

        var next7days =  new Date(today.setDate(today.getDate()+6));
        _next7days = "Dự báo từ ngày "+(today.getDate()-6)+" đến ngày "+next7days.getDate()+" "+Localtime.convertMonth(next7days.getMonth());
        $("#forecast_7days").attr("title",""+_next7days);
    },

    /**
     * convert Mon-Sun or 0-6 to Vietnamese Thu 2,3
     * @param String day
     */
    convertDay:function(day){
        var isDigit = /^-?\d+$/.test(day);
        if(isDigit == false){
            //if day == int then remove comma (Tue,) first before convert
            var day = day.split(",");
            day = day[0];
        }

        if(day == "Mon" || day == "1")
        {return "Thứ hai";}
        else if(day == "Tue"|| day == "2")
        {return "Thứ ba";}
        else if(day == "Wed"|| day == "3")
        {return "Thứ tư";}
        else if(day == "Thu"|| day == "4")
        {return "Thứ năm";}
        else if(day == "Fri"|| day == "5")
        {return "Thứ sáu";}
        else if(day == "Sat"|| day == "6")
        {return "Thứ bảy";}
        else if(day == "Sun"|| day == "0")
        {return "Chứ nhật";}
    },

    /**
     * convert english month to Vietnamese
     * @param String
     */
    convertMonth:function(month){
        if(month == "Jan" || month == 0 )
        {return "Tháng 1";}
        else if(month == "Feb"|| month == 1)
        {return "Tháng 2";}
        else if(month == "Mar"|| month == 2)
        {return "Tháng 3";}
        else if(month == "Apr"|| month == 3)
        {return "Tháng 4";}
        else if(month == "May"|| month == 4)
        {return "Tháng 5";}
        else if(month == "Jun"|| month == 5)
        {return "Tháng 6";}
        else if(month == "Jul"|| month == 6)
        {return "Tháng 7";}
        else if(month == "Aug"|| month == 7)
        {return "Tháng 8";}
        else if(month == "Sep"|| month == 8)
        {return "Tháng 9";}
        else if(month == "Oct"|| month == 9)
        {return "Tháng 10";}
        else if(month == "Nov"|| month == 10)
        {return "Tháng 11";}
        else if(month == "Dec"|| month == 11)
        {return "Tháng 12";}
    }
}

var Forecast ={
    weather:function()
    {
        //AJAX XML
        $.ajax({
            type: "POST",
            url: "proxy.php",
            data: {long:_longitude, lat:_latitude, gmt:_GMT, currentUnixTime:_CurrentUnixTime,when:_when},
            dataType: "json",
            beforeSend:function(){
            		Helper.ajaxloader("on");	
            },
            //timeoutNumber: 4000,
            success: function(data) {

                //save this data the variable
                _xmldata = data;

                //send to another function for html
                Helper.weatherReport();

            },
            complete:function (xml) {
                //console.log("REMOVE LOADER");
            }
        });
    }
}

var Search={
    Google_API:"ABQIAAAAwpCf2yjiVxoRDi894zq1NxRKDLeukDAOFaa-A_-8ihap8BQAMBSc0ajNEdVP4L5G9tIr87Qi6Px90Q",

    city:function()
    {
        var city = $("#city_input").val();
        if( city != "")
        {
            //AJAX XML
            $.ajax({
                type: "GET",
                url: "http://maps.google.com/maps/geo?q="+city+"&output=json&sensor=true&key="+Search.Google_API+"&callback=?",
                dataType: "json",
                success: function(data) {
                    if(data.Status.code = 200){
                        if(data.Placemark.length < 2){

                            //Set lat,long for later use to Forecast.weather()
                            _latitude = data.Placemark[0].Point.coordinates[1];
                            _longitude = data.Placemark[0].Point.coordinates[0];
                            //console.log("lat: "+_latitude +" - lon: "+_longitude);

                            //replace the city name header
                            _cityCountry = data.Placemark[0].address;
                            _when = "today";
                            Helper.changeCityHead();

                        }
                        else{
                            $.each(data.Placemark, function(i, place){
                                //console.log("many places?");
                                //console.log(place);
                                return false;
                            });
                        }
                    }
                },
                complete:function (data) {
                    //console.log("REMOVE LOADER");
                    Localtime.getTime();
                },
                error:function(data){
                    //console.log("error :"+data);
                }
            });
        }

    }
}

var Helper ={
    changeCityHead:function()
    {
        $("#city_name").text(_cityCountry);

        $("#forecast_options ul li").removeClass("active");
            
        //change to date to header
        if(_when == "today")
        {
            $("#myDate p").text(_today);
            $("#forecast_today").parent().addClass("active");
        }
        else if(_when == "tomorrow")
        {
            $("#myDate p").text(_tomorrow);
						$("#forecast_tomorrow").parent().addClass("active");
        }
        else if(_when == "next7days")
        {
            $("#myDate p").text(_next7days);
            $("#forecast_7days").parent().addClass("active");
        }
    },

    weatherReport:function()
    {
        $("#forecasts").empty();
        //$("#forecasts").append("<ul>");

        if($(_xmldata).length < 1)
        {
            /**
             * TODO when xml return zero, it
             * means no data avail. we need to go to next day
             */
             if(_tried < 2)
             {
             		_when = "tomorrow";
             		_tried++;	
             }
             else{
	             _when = "today";
	            _tried = 0;
          	}
          		
            Forecast.weather();
          	return false;
        }

        //start the html string
        var htmlstring = "<ul>";
        var li = 0;
        var childInXml = 0;

        $.each(_xmldata, function(i,item){
            //date":"2010-Mar-15 11:00","temperature":"21.8","id":"CLOUD","number":"4"

            //split the date
            var dateArray = item.date.split(" ");

            var hour = dateArray[1];
            dateArray = dateArray[0].split("-");
            //var month = Localtime.convertMonth(dateArray[1]);

            var temperature = Math.round(item.temperature);
            var hotcold = "minus";
            if(temperature > 0)
            {
                hotcold = "plus";
            }

            //change the number from 1 -> 01
            var number = item.number;

            if(parseInt(item.number) < 10)
            {
                number = "0"+item.number;
            }

            //if we are at day
            if(parseInt(item.number) < 9)
            {
                if(parseInt(item.number) != 4)
                {
                    if(item.hour > 18 || item.hour < 5 )
                    {
                        number = number+"n";
                    }
                    else{
                        number = number+"d";
                    }
                }
            }

            //we need to close the ul if <li> is 3
            if(li == 3)
            {
                htmlstring +="</ul><ul class='hideme'>";
                li = 0;
            }


            htmlstring +='<li><h2>'+hour+'</h2><p><img src="img/'+number+'.png" alt="'+item.date+'" /><span class="temperature '+hotcold+'">'+temperature+'<span class="celsius">&#8451;</span></span></p></li>'


            li++;
            childInXml++;

            //this is final close </ul>.break 
            if($(_xmldata).length == childInXml)
            {
                htmlstring += "</ul><div id='navigator' class='hideme'><p><a href='#' id='goprev' name='goprev'><img src='img/prev.png' alt='View previous data' /></a> <a href='#' id='gonext' name='gonext'><img src='img/next.png' alt='See more data..' /></a></p></div>";
            }
        });

        $("#forecasts").prepend(htmlstring);

        //hide all <ul> first
        $("#forecasts ul").first().removeClass("hideme");

        //now display the first <ul> only
        $("#forecasts ul").first().removeClass("hideme");

        //and then display the navigator
        if(parseInt(childInXml) > 3)
        {
            $("#navigator").removeClass("hideme");
            Helper.navidator();
        }

        //change to current city to user's city
        Helper.changeCityHead();
        
        //add onlick for navidator btn
        $("#gonext").click(function(){
            Helper.goNext();
            return false
        });
        $("#goprev").click(function(){
            Helper.goPrev();
            return false
        });
        
    },

    navidator:function()
    {

        // As long the first <ul> is not class hideme
        // then display the it prev button
        if($("#forecasts ul:first-child").attr("class") == "hideme")
        {
            $("#goprev").removeClass("hideme");
        }
        else
        {
             $("#goprev").addClass("hideme");
        }

        // As long as the last <ul> doesnt have
        // class hideme we can display the next button
        if($("#forecasts ul").last().attr("class") == "hideme")
        {
            $("#gonext").removeClass("hideme");
        }
        else
        {
             $("#gonext").addClass("hideme");    
        }
    },

    goNext:function()
    {
        var currentNode = $("#forecasts ul").not('.hideme');

        //now we hide it...
        $(currentNode).addClass("hideme");

        //but also need to show the next node
        $(currentNode).next("ul").removeClass();

        Helper.navidator();
    },

    goPrev:function()
    {
        var currentNode = $("#forecasts ul").not('.hideme');

        //now we hide it...
        $(currentNode).addClass("hideme");

        //but also need to show the next node
        $(currentNode).prev("ul").removeClass();

        Helper.navidator();
    },
    ajaxloader:function(on)
    {
    		if(on == "on")
    		{
    				$("#forecasts").append("<p id='ajaxloader'>Please wait...</p>");
    		}			
    		else{
    				//$("#forecasts")		
    		}
    		
    }
}
