
STAT_TIMEOUT_ID = null;
CLOSE_STATUS_DELAY = 3500;
FETCHING_SUGGEST = false;
RADAR_BASE_PATH = 'http://weather.ninemsn.com.au/radar.jsp';
WEATHER_BASE_PATH = 'http://weather.ninemsn.com.au/';
SYD_LOCAL_URL = 'http://weather.ninemsn.com.au/nsw/sydney/sydney';
SYD_LOCAL_RADAR = 'http://weather.ninemsn.com.au/radar.jsp?lt=radar&lc=003';


weatherItemObj = function(day, imgURL, tempStr)
{
    this.day = day;
    this.imgURL = imgURL;
    this.tempStr = tempStr;
}

cookieCallBack = function(data)
{
    try
    {
        if((data.ProfileResult != '') && (data.ProfileResult != '2000') )
        {
            getWeatherData(data.ProfileResult, true)
        }
        else
        {
            getDataFromHL();
        }
    }
    catch(e)
    {
        getDataFromHL();
    }
}

checkPCodeCookie = function()
{
    Ninemsn.Site.NH.Profile.Get("postcode", cookieCallBack); 
}

setPCodeCookie = function(pCode)
{      
    Ninemsn.Site.NH.Profile.Set("postcode", pCode);
}

getDataFromHL = function()
{
    var title = $('#cat_hl_87816 .orderedItem1').eq(0).text();
    var curr = $('#cat_hl_87816 .orderedItem1').eq(0).attr('href');
    var items = $('#cat_hl_87816 .lvl2');
    var itemArray = [];
    
    items.each(function(i)
    {
        var linkItem = $(this).find('.linkItem').eq(0);
        var itemImg = $(this).find('img').eq(0);
        
        if(i==0)
        {
            itemArray.push(new weatherItemObj('Today', itemImg.attr('src'), itemImg.attr('alt')));  
        }
        else
        {
            itemArray.push(new weatherItemObj(linkItem.text(), itemImg.attr('src'), itemImg.attr('alt')));
        }
                  
    });
    
    renderWeatherUI(title, curr, itemArray, SYD_LOCAL_URL, SYD_LOCAL_RADAR); 
              
}

weatherDataCallback = function(data)
{
    if(data)
    {     
        try
        {       
            var loc = data.data.weather.countries.country.location;
            
            if(loc.length)
            {
                var res = $('#wm_result_box');
                res.children().remove();
                for(i=0;i<loc.length;i++)
                {                  
                   var opt = $('<div></div>').text(loc[i].name + ', ' + loc[i].state).click(optionClick).hover(optionMOver,optionMOut).data('data', loc[i]);
                   res.append(opt);        
                }
                
                toggleSuggest(false);
                
                $('#wm_result_ctnr').fadeIn('slow', function()
                {
                    if(jQuery.browser.msie)
				        $(this).get(0).style.removeAttribute('filter');
                });
            }
            else
            {
                extractData(loc); 
            }
        }
        catch(e)
        {
            showMsg('No results were found.  Please try again...', '/img/lcm_find/info.gif', true);
        }      
    }
    else
    {
        showMsg('Weather service temporarily unavailable.', '/img/lcm_find/error.gif', false);
    }                   
}

suggestDataCallBack = function(data)
{
    if(data)
    {     
        try
        {       
            var loc = data.data.weather.countries.country.location;
            var res = $('#wm_suggest');
            res.children().remove();
            if(loc.length)
            {                
                for(i=0;i<loc.length;i++)
                {
                   var opt = $('<div></div>').text(loc[i].name + ', ' + loc[i].state).click(optionClick).hover(optionMOver,optionMOut).data('data', loc[i]);
                   res.append(opt);        
                }
            }
            else
            {
               var opt = $('<div></div>').text(loc.name + ', ' + loc.state).click(optionClick).hover(optionMOver,optionMOut).data('data', loc);
               res.append(opt); 
            }
            toggleSuggest(true);            
        }
        catch(e)
        {
            toggleSuggest(false); 
            
            FETCHING_SUGGEST = false;      
        }      
    }
    FETCHING_SUGGEST = false;
}

extractData = function(locData)
{
    var title = 'Weather';
    var curr = '';
    var postcode = '';
    var links = [];
    var k,l;
    
    try
    {       
        var localLinks = locData.links.link;
        var radarURL = '';
        var localURL = '';
        for(l=0;l<localLinks.length;l++)
        {
            var curLink = localLinks[l];
            if(curLink.type == 'radar')
            {
                radarURL = WEATHER_BASE_PATH + curLink.url.substring(30);
            }
            if(curLink.type == 'local')
            {
                localURL = WEATHER_BASE_PATH + curLink.url.substr(30);
            }
        }
        
        radarURL = (radarURL != '' ? radarURL : RADAR_BASE_PATH);
        localURL = (localURL != '' ? localURL : WEATHER_BASE_PATH);       

        for(k=0;k<4;k++)
        {
            var item = locData.forecasts.forecast[k];
            
            var day = (item.day_name && (item.day_name != '')) ? item.day_name.substr(0,3) : '';
            var imgURL = ((item.icon.filename != '')) ? '/img/lcm_find/weather_icons/' + item.icon.filename : '';  
            var tempMin = (item.temp_min_c && item.temp_min_c.value && (item.temp_min_c.value != '')) ? item.temp_min_c.value + '&deg;' : '';
            var tempMax = (item.temp_max_c && item.temp_max_c.value && (item.temp_max_c.value != '')) ? item.temp_max_c.value + '&deg;' : '';   
            
            if(k == 0)
            {
                day = 'Today';
            }
          
            links.push(new weatherItemObj(day, imgURL, tempMin + '/' + tempMax));                      
        }
        
        if (locData.name && (locData.name != '') && locData.conditions && locData.conditions.temp_c && (locData.conditions.temp_c.value != ''))
        {
            curr = 'Currently ' + locData.conditions.temp_c.value + '&deg; in ' + locData.name;
        }
        
        if(locData.postcode && (locData.postcode != ''))
        {
            setPCodeCookie(locData.postcode);
        }
        
        renderWeatherUI(title, curr, links, localURL, radarURL);            
    }
    catch(e)
    {
        toggleSuggest(false); 
        showMsg('Weather service temporarily unavailable.', '/img/lcm_find/error.gif', false);     
    }   
    
}


renderWeatherUI = function(title, curr, links, localURL, radarURL)
{
    var mod = $('#weatherModule');
    $('#wm_suggest div').remove();
        
    if(!mod.children().length)
    {         
        var head = $('<div></div>').attr('id', 'wm_top');
        var headLink = $('<a></a>').attr({'id':'wm_title','href':'http://weather.ninemsn.com.au/'}).html('<h2>' + title + '</h2>');
        var currTxt = $('<div></div>').attr('id', 'wm_curr').html(curr);
        head.append(headLink).append(currTxt);
                
        var contentWrap = $('<div></div>').attr('id', 'wm_content_wrap');
        var content = $('<div></div>').attr('id', 'wm_content');
        
        var resultCtnr = $('<div></div>').attr('id', 'wm_result_ctnr');
        var resultLbl = $('<div></div>').attr('id', 'wm_result_lbl').text('Please choose a location');
        var resultBox = $('<div></div>').attr('id', 'wm_result_box');
        resultCtnr.append(resultLbl).append(resultBox);
        
        var statusCtnr = $('<div></div>').attr('id', 'wm_status_ctnr');
        var statusImg = $('<img/>').attr('id', 'wm_status_img');
        var statusTxt = $('<div></div>').attr('id', 'wm_status_txt');
        statusCtnr.append(statusImg).append(statusTxt);              
        
        for(i=0;i<links.length;i++)
        {
            var item = links[i];
            var ctnr = $('<div></div>').attr('id', 'wm_day' + (i+1));
            
            if(i==0)
            {
                ctnr.addClass('first_day');  
            }
            
            var imgLink = $('<a></a>').attr({'href':localURL, 'class':'wm_img_link'});
            var dayImg = $('<img/>').attr('src', item.imgURL);
            imgLink.append(dayImg);
            
            var day = $('<div></div>').attr('class', 'wm_date');
            var dayLink = $('<a></a>').attr('href', localURL).text(item.day);
            day.append(dayLink);
            
            var temp = $('<div></div>').attr('class', 'wm_temp').html(item.tempStr);
            ctnr.addClass('wm_day').append(imgLink).append(day).append(temp);
            
            content.append(ctnr);            
            
        }
        
        var linkCtnr = $('<div></div>').attr('id', 'wm_link_ctnr');
        var moreArr = $('<img/>').attr({'src':'/img/global/icn-arrow.gif', 'id':'wm_moreArr'});
        var moreLink = $('<a></a>').attr({'class':'wm_more_link','href':WEATHER_BASE_PATH, 'title':'More weather'}).text('More weather');
        var radarArr = $('<img/>').attr({'src':'/img/global/icn-arrow.gif', 'id':'wm_radarArr'});
        var radarLink = $('<a></a>').attr({'class':'wm_radar_link','href':radarURL, 'title':'Radar'}).text('Radar');
        linkCtnr.append(moreArr).append(moreLink).append(radarLink).append(radarArr);
                
        var bottom = $('<div></div>').attr('id', 'wm_bottom');
               
        var pCodeCtnr = $('<div></div>').attr('id', 'wm_pcode');
        var pCodeLbl = $('<span></span>').attr('id', 'wm_fc').text('Local forecast:');
        var pCodeTxtBx = $('<input type="text" />').attr({'id':'wm_txtbox','autocomplete':'off'}).val('Enter postcode or location').bind('keypress', wmTxtBoxKeyPress).click(wmTxtBoxClick).bind('focus',wmTxtBoxFocus);
        var pCodeGo = $('<input type="image"/>').attr({'id':'wm_submit', 'src':'/img/lcm_find/bluego.gif'}).click(wmGoClick);    
        var suggCtnr = $('<div></div>').attr('id', 'wm_suggest');
        pCodeCtnr.append(pCodeLbl).append(pCodeTxtBx).append(pCodeGo).append(suggCtnr);       
        
        bottom.append(pCodeCtnr);
        contentWrap.append(content).append(resultCtnr).append(statusCtnr);    
        mod.append(head).append(contentWrap).append(linkCtnr).append(bottom);
    }
    else
    {
        var content = $('#wm_content');
        var currElem =  $('#wm_curr');
        content.css('display', 'none');
        currElem.css('display', 'none');
        
        currElem.html(curr);
                                
        for (j=0;j<links.length;j++)
        {
            var linkItem = links[j];
            
            content.find('.wm_img_link').eq(j).attr('href',localURL);
            content.find('img').eq(j).attr('src', linkItem.imgURL);
            content.find('.wm_date a').eq(j).attr('href', localURL).text(linkItem.day);
            content.find('.wm_temp').eq(j).html(linkItem.tempStr);
        }
        
        $('#weatherModule .wm_radar_link').eq(0).attr('href',radarURL); 
        
        
        content.fadeIn("slow", function()
        {
            if(jQuery.browser.msie)
				$(this).get(0).style.removeAttribute('filter');
        })
        currElem.fadeIn("slow", function()
        {
            if(jQuery.browser.msie)
				$(this).get(0).style.removeAttribute('filter');
        });
    }   
       
}

getWeatherData = function(loc, isPcode)
{            
    var weatherService;
    if(isPcode)
    {
        weatherService = 'http://data.ninemsn.com.au/Services/Service.axd?ServiceFormat=JSONAUTO&ServiceAction=SearchPostCode&Params=%26pc='+ loc + '%26obs=1%26fc=1%26days=4%26rollover=24%26links=1&ServiceName=Weather&callback=?';
    }
    else
    {
        weatherService = 'http://data.ninemsn.com.au/Services/Service.axd?ServiceFormat=JSONAUTO&ServiceAction=SearchPostCode&Params=%26ln='+ loc + '%26obs=1%26fc=1%26days=4%26rollover=24%26links=1&ServiceName=Weather&callback=?';
    }
     
    $.getJSON(weatherService, weatherDataCallback);
}

getSuggestData = function()
{
    if(!FETCHING_SUGGEST)
    {
        FETCHING_SUGGEST = true;
        weatherService = 'http://data.ninemsn.com.au/Services/Service.axd?ServiceFormat=JSONAUTO&ServiceAction=SearchPostCode&Params=%26ln='+ $('#wm_txtbox').val() + '%26obs=1%26fc=1%26days=4%26rollover=24%26links=1&ServiceName=Weather&callback=?';
        $.getJSON(weatherService, suggestDataCallBack);
    }
}
    
showMsg = function(msgTxt, imgSrc, timer)
{       
    $('#wm_status_img').attr('src',imgSrc);
    $('#wm_status_txt').text(msgTxt);
    
    $('#wm_status_ctnr').fadeIn('slow', function()
    {
        if(jQuery.browser.msie)
				$(this).get(0).style.removeAttribute('filter');
    });
    
    if(timer)
    {
        STAT_TIMEOUT_ID = setTimeout(closeStatus, CLOSE_STATUS_DELAY);
    }   

}

toggleSuggest = function(show)
{
    var sugg = $('#wm_suggest');
    var opts = $('#wm_suggest div').filter(':visible');
    
    if(show && opts.length)
    {
        var len = opts.length * 16;
        
        if(len != 0)
        {
           if((len >= 100))
            {
                sugg.animate({'height': 100}, 'fast').css({'display':'block','border': '1px solid #A0A0A0', 'borderTop':'0px none'}, 'fast', function()
                {
                    $(document).bind('click', wmTxtBoxBlur); 
                });           
            }
            else
            {
                sugg.animate({'height': len}, 'fast').css({'display':'block','border': '1px solid #A0A0A0', 'borderTop':'0px none'}, 'fast', function()
                {
                    $(document).bind('click', wmTxtBoxBlur); 
                });
            }    
        }       
    }
    else
    {
        sugg.animate({'height': '1px'}, 'fast', function()
        {
            $(this).css({'display':'none','border':'0px none'}, 'fast', function()
            {
                $(document).unbind('click', wmTxtBoxBlur); 
            });
        })
    }
}

checkTextBox = function()
{
    var numcheck = /\d/;
    var bxVal = $('#wm_txtbox').val();
    if(!numcheck.test(bxVal) && (bxVal.length == 2) )
    {
        getSuggestData();
    }
    else if(!numcheck.test(bxVal) && (bxVal.length > 2))
    {
        filterResults();
    }
    else
    {
        toggleSuggest(false);
        $('#wm_suggest div').remove();
    }        
}

filterResults = function()
{
    var opts = $('#wm_suggest div');

    var bxVal = $('#wm_txtbox').val().toLowerCase();
    
    opts.each(function(i)
    {
        var name = $(this).data('data').name.substr(0,bxVal.length).toLowerCase();
        var match = name.match(bxVal);
        if(match && (match != -1))
        {
            $(this).css('display', 'block');
        }
        else
        {
            $(this).css('display', 'none');
        }   
    });
   
    toggleSuggest(true);
    
}

/***** Event Handlers ********/

closeStatus = function()
{
    if($('#wm_status_ctnr').is(':visible'))
    {
        $('#wm_status_ctnr').fadeOut('slow', function()
        {
            if(jQuery.browser.msie)
				$(this).get(0).style.removeAttribute('filter');
        });
    }
}

wmTxtBoxKeyPress = function(e)
{
    var evt=(e)?e:(window.event)?window.event:null;
 
    if(evt)
    {
        var key=(evt.charCode)?evt.charCode:((evt.keyCode)?evt.keyCode:((evt.which)?evt.which:0));
        
        if (key == "13")
        {
            toggleSuggest(false);
            wmGoClick();
            return false;
        }
        else
        {
            setTimeout(checkTextBox, 5);
        }
    }
    return true;
}

wmTxtBoxBlur = function()
{
    toggleSuggest(false);
}

wmTxtBoxFocus = function()
{
    toggleSuggest(true);
}

wmTxtBoxClick = function(e)
{
    if($(this).val() == 'Enter postcode or location')
    {
        $(this).val(''); 
    }
    return true;
}

wmGoClick = function(e)
{     
   var loc = $('#wm_txtbox').val();
   
   toggleSuggest(false);
   
   if ((loc == '') || loc == 'Enter postcode or location')
   {
       showMsg('Please enter a valid location or postcode.', '/img/lcm_find/info.gif', true);
   }
   else if (!isNaN(loc))
   {
       if(loc.match(/\d{4}/))
       {
           getWeatherData(loc, true);   
       }
       else
       {
           showMsg('Please enter a valid 4 digit postcode.', '/img/lcm_find/info.gif', true);
       }
   }
   else
   {
       getWeatherData(loc, false); 
   }
      
   return false;
}

optionClick = function()
{
    if($('#wm_result_ctnr').is(':visible'))
    {
       $('#wm_result_ctnr').fadeOut('slow', function()
       {
        if(jQuery.browser.msie)
		    $(this).get(0).style.removeAttribute('filter');
       }); 
    }
    
    toggleSuggest(false);
        
    extractData($(this).data('data')); 
}

optionMOver = function()
{
    $(this).addClass('hover');
}

optionMOut = function()
{
    $(this).removeClass('hover');
}
