/// <reference path="MDSMapIntelliSenseHelper/MDSMapIntelliSenseHelper.js" />

// Load/Unload map

var _map = null;
var _LastInput = {
    Town: "",
    State: "" 
    };  

//Page buffer
var _FindLoc = {
x:0, //Address Location X
y:0, //Address Location Y
Address:""
}
 
var rList_strVal;  //= new Array();  
var rList_x; //= new Array();
var rList_y; //= new Array();
var rList_tot;
var rList_Dist;
var NumPerList = 5;
var g_CurrentPageNo=0;
var g_endPage = 0;

var _RadioSel = {
    Predealers: "radPredealers",
    Windscreen: "radWindscreen", 
    Repairs: "radRepairs",
    Caltex: "radCaltex", 
    Tyres: "radTyres",
    Batteries: "radBatteries" 
    }; 

var _PageStatus = {
    OnLoadMap: "OnLoadMap",
    MapPage: "MapPage"
    };
    
//For map move
var _CurrentSQL = {
    type: 0, //Current search SQL type value {1,2,3,4,5,6}
    sql: "",
    pagenum: 0,
    cx: 0,
    cy: 0
    };


function loadMap() 
{
    _map =new MDSMap($get('MapWindow'));  
    _map.UserIDSet($get('UserID').value);    
    _map.LoadMap(null,null,747,395,850,500)
    SetPageVisible(_PageStatus.OnLoadMap)
}


function unloadMap() 
{
    _map.UnloadMap();
}

function SearchClick() 
{
    SearchClickBody();
}

function SearchClickBody()
{
var st = $get('txtSuburb').value; //Town or Postcode
var state = $get('selState').value; 
   
    if ((st !== _LastInput.Town) || (state !== _LastInput.State)) FindLoc(st, state); //when multiple select, user input new town name
    else {if ($get('cboLoc').style.display !='none') 
        {
            if ($get('cboLoc').options[$get('cboLoc').selectedIndex].value !="0") 
            {
                $get('cboLoc').style.display='none';
                $get('errorMsg').style.display='none';
             
         
                var LatLong=$get('cboLoc').options[$get('cboLoc').selectedIndex].value.split("***");
                $get('selState').value = LatLong[2];
                if ($get('txtSuburb').value !="")
                {
                    _FindLoc.x = LatLong[0];
                    _FindLoc.y = LatLong[1];
                    _FindLoc.Address = $get('cboLoc').options[$get('cboLoc').selectedIndex].text;
                    initSearch(LatLong[0],LatLong[1]);
                }
            }
        }
    else checkFormValid();}
}

function checkFormValid() {
    
    var st = $get('txtSuburb').value; //Town or Postcode
    var state = "";
    if ($get('selState').value != '') state = $get('selState').value; 
    
    if (st !="") 
    {
        FindLoc(st, state);
    }    
    else
    {
        $get('errorMsg').style.display='';
        $get('errorMsg').innerHTML = '*Please provide a suburb or postcode to proceed with search.';
    }       
}

function MapMove(e) {

    //var cLatLong = _map.CentreLatLong();
    
    if ((_CurrentSQL.type == 1) || (_CurrentSQL.type == 2) ||  (_CurrentSQL.type == 3))
    {   
    //GeneralSearch.FindNearestVineInit($get('UserID').value,_CurrentSQL.type,_CurrentSQL.cx,_CurrentSQL.cy,_CurrentSQL.sql,0,VineSearchCallBack)
    }
}


function FindLoc(adr,state)
{
    _LastInput.Town=adr;
    _LastInput.State=state;
    QLPipe.FindSuburb($get('UserID').value,adr,state,FindLocCallBack);
}

function FindLocCallBack(results)
{
    var cboLoc = $get('cboLoc');
    $get('errorMsg').style.display='none';
    
    switch(results.FullResult)
    {
        case 1://one addy                
            //_map.ZoomToPoint(results.Locations[0].Position.Y, results.Locations[0].Position.X, 13);
            $get('cboLoc').style.display='none';
            $get('errorMsg').style.display='none';
            
            _FindLoc.x = results.Locations[0].Position.X;
            _FindLoc.y = results.Locations[0].Position.Y;
            if (results.Locations[0].Suburb=="")
            {
            _FindLoc.Address = results.Locations[0].Postcode + "," + results.Locations[0].State;
            }
            else 
            {
            _FindLoc.Address = results.Locations[0].Suburb + "," + results.Locations[0].State;
            }
            
            initSearch(results.Locations[0].Position.X,results.Locations[0].Position.Y);
            break;
        case 100://multi address
            cboLoc.style.display='';
            $get('errorMsg').style.display='';
            $get('errorMsg').innerHTML="*Multiple results were found. Please select the best match from the list.";
            cboLoc.options.length=0;
            cboLoc[0]=new Option("Please select...","0");
            
            for(var a=0;a<results.Locations.length;a++)//populate the combobox with locations
            {
                var obj=new Option(results.Locations[a].Suburb+", "+results.Locations[a].State+", "+results.Locations[a].Postcode,results.Locations[a].Position.X+"***"+results.Locations[a].Position.Y+"***"+results.Locations[a].State);
                cboLoc[a+1]=obj;
            }
            break
        default://no addy//invalid addy
            $get('cboLoc').style.display='none';
            $get('errorMsg').style.display='';
            $get('errorMsg').innerHTML="*No match was found for the Suburb/postcode. Please check the suburb/postcode.";
            globErr=true;
            break;
    }
}

function initSearch(x,y)
{
    var option = "";
    var subOption = "";
    var tot = $get('selResultNo').value;       
    CleanupArray();    
    option = BuildOption();
    if (option == _RadioSel.Predealers) 
    { if ($get('selManufac').value=='0') 
            { $get('errorMsg').style.display='';
              $get('errorMsg').innerHTML="*You have not made a choice for vehicle make. Please select a manufacturer to proceed with search.";
              return false;
            }
      else subOption = $get('selManufac').value;
    }
    if (option == _RadioSel.Repairs) 
    { if ($get('selManufac').value=='0') 
            { $get('errorMsg').style.display='';
              $get('errorMsg').innerHTML="*Please select a Manufacturer.";
              return false;
            }
      else subOption = $get('selManufac').value;
    }    
    if (option == _RadioSel.Tyres) 
    { if ($get('selBrand').value == '0') 
            { $get('errorMsg').style.display='';
              $get('errorMsg').innerHTML="*Please select a Brand.";
              return false;
            }
      else subOption = $get('selBrand').value;
    }  
    if (option == _RadioSel.Caltex) 
    { if ($get('selFuel').value=='0') 
            { $get('errorMsg').style.display='';
              $get('errorMsg').innerHTML="*Please select a brand of fuel.";
              return false;
            }
      else subOption = $get('selFuel').value;
    }    

    GeneralSearch.FindNearestOrix($get('UserID').value,x,y,option,subOption,tot,OrixSearchCallBack)
    DisplayProcessingInfo();
  
}

function OrixSearchCallBack(results)
{
    UndisplayProcessingInfo();
    OrixSearchCallBack(results);
}

function OrixSearchCallBack(results) {

    var dt;
    var fieldL;
    var LocationTypeIDs;
    var iconPath;
    var j = 0;
    var strDest = "";
    var companyPhone="";
       
    _map.Markers.Clear();
    g_TotalResults=results.tot;
    
    if(results.tot==0) 
    {
        dt = results.tot.toString();
        $get('errorMsg').style.display='';
        $get('errorMsg').innerHTML = '*The data for option selected is not available. Please try other options.';
        $get('mapFrame').style.display='none'; 
        
    } 
    else 
    {
         $get('copyright').style.display='none'; //gets rid of copyright at bottom of search   
        rList_strVal = new Array();
        rList_x = new Array();
        rList_y = new Array();
        rList_Dist = new Array();
         
        for (var mc=1;mc<=results.tot;mc++) 
        {
            j++;
            var newMarker = new MDSMarker( new MDSLatLong( results.Items[mc].Y, results.Items[mc].X ) );
            newMarker.SetClassName('marker');
            newMarker.SetCaption(j);
            fieldL = results.Items[mc].StringVal.split("***");
            
            strDest = fieldL[1]+'|'+fieldL[2]+'|'+fieldL[7];
            strDest = RemoveBadChar(strDest);
            strDest = "'" + strDest+"'";
            iconPath = "images/redpoint1.png";
            newMarker.SetIcon(iconPath, 20, 20,0,10);
            
            if (fieldL[5]=='Battery World') companyPhone = '1300 MARSHALL (1300 6277 4255)';
            else if (fieldL[5]=='Marshall') companyPhone = '13 17 60';
            else if (fieldL[5]=='Instant Windscreens') companyPhone = '13 24 44';
            else if (fieldL[5]=='NOVUS Autoglass') companyPhone = '13 22 34';
            else if (fieldL[5]=='Obrien Glass') companyPhone = '1800 645 011';
            else companyPhone = fieldL[4]; 
            
            if (fieldL[5]=='SHELL')
            {
            var popContent =
                         '<ul>' +
            '<li ><div class="markerFont">Type:</div></li><li>'+fieldL[1]+'</li>'+
            '<li ><div class="markerFont">Name:</div></li><li>'+fieldL[2]+'</li>'+
            '<li ><div class="markerFont">Address:</div></li><li>'+fieldL[3]+'</li>' +
            '<li ><div class="markerFont">Phone:</div></li><li>'+companyPhone+'</li>' +
            '<li ><div class="markerFont">Distance(km):</div></li>' +
            '<li >' + results.Items[mc].Distance.toFixed(1) +'</li>'+
            '<li ><div class="markerFont"><a href="http://www.shell.com.au/fuelfinder" target="about:blank">Visit Shell&#39;s Online Fuel Finder</a></div></li>';
            
            if (fieldL[6]=='Yes') 
            {
            popContent+= '<br/><li ><div style="color:Red;font-weight:bold;">Temporarily Closed</div></li>';
            }
            
            popContent+= '</ul>';
            newMarker.SetPopupContent(popContent);
            }
            else
            {
            newMarker.SetPopupContent( '<ul>' +
            '<li ><div class="markerFont">Type:</div></li><li>'+fieldL[1]+'</li>'+
            '<li ><div class="markerFont">Name:</div></li><li>'+fieldL[2]+'</li>'+
            '<li ><div class="markerFont">Address:</div></li><li>'+fieldL[3]+'</li>' +
            '<li ><div class="markerFont">Phone:</div></li><li>'+companyPhone+'</li>' +
            '<li ><div class="markerFont">Distance(km):</div></li>' +
            '<li >' + results.Items[mc].Distance.toFixed(1) +'</li>'+
            '</ul>');
            }
            
            newMarker.SetPopupDisplay( MDSPopupDisplay.MouseOver );
            _map.Markers.Add( newMarker );
            rList_strVal[mc] = results.Items[mc].StringVal;
            rList_x[mc]= results.Items[mc].X;
            rList_y[mc]= results.Items[mc].Y;
            rList_Dist[mc] = results.Items[mc].Distance.toFixed(1);
                   
        }
        addLocMarker();
        rList_tot = results.tot; 
        var iFor = "";
        g_endPage = (results.tot/NumPerList);
        g_endPage = parseInt(g_endPage);            
        if ((results.tot % NumPerList) > 0) g_endPage += 1;
  
        if (g_endPage >1) //don't show page, result is only one
        {
            for (var mc=1;mc<=g_endPage;mc++) 
            { 
                iFor += '<a href="javascript:ListByPageNo(' + mc+') ">' + mc+'</a>.';                    
            }
            $get('indRight2').innerHTML = iFor; 
            // $get('indRightb2').innerHTML = iFor;
            $get('indRight3').innerHTML = "<a href='javascript:ListByPageNo(2)'>Next</a>";
            //$get('indRightb3').innerHTML = "<a href='javascript:ListByPageNo(2)'>Next</a>";
        }
        
        if (g_endPage == 2) 
            {$get('indRight2').style.width=25; 
           // $get('indRightb2').style.width=25;
        }
        if (g_endPage == 3) 
        {   $get('indRight2').style.width=35; 
            // $get('indRightb2').style.width=35;
        }
        if (g_endPage >= 4) 
            {$get('indRight2').style.width=45; 
           //  $get('indRightb2').style.width=45;
        } 
        
        if (results.tot <= NumPerList) 
        { 
        $get('indLeft1').innerHTML = rList_tot + " locations, displaying 1 - " + results.tot;
        //$get('indLeftb1').innerHTML = rList_tot + " locations, displaying 1 - " + results.tot;
        }
        else
        {
        $get('indLeft1').innerHTML = rList_tot + " locations, displaying 1 - " + NumPerList;
       // $get('indLeftb1').innerHTML = rList_tot + " locations, displaying 1 - " + NumPerList;
        }
        ListByPageNo(1);
         
        _map.Refresh();
        var cLatLong = _map.CentreLatLong();
        _CurrentSQL.cx = cLatLong.Long;
        _CurrentSQL.cy = cLatLong.Lat;        
    }    
}
//To show the view of user address and the target points, add user loc into Markers. 
function addLocMarker()
{
    var newMarker = new MDSMarker( new MDSLatLong( _FindLoc.y, _FindLoc.x ) );
    newMarker.SetClassName('marker');
    //newMarker.SetCaption(j);
    var iconPath = "images/Pin.gif";
    newMarker.SetIcon(iconPath, 18, 19, 0, 2);
            
    newMarker.SetPopupContent( '<ul>' +
    '<li ><div class="markerFont">Address:</div><li >' + _FindLoc.Address+'</li></ul>');
    newMarker.SetPopupDisplay( MDSPopupDisplay.MouseOver );
                       
    _map.Markers.Add( newMarker );

}

function ListByPageNo(Page) 
{
        var fieldL;
        var dt;
        var strDest = "";
        var startPos = (Page*NumPerList)-NumPerList+1;
        var endPos = Page*NumPerList;
        var trColour = '"#ffffff"';
        var trClass = '"odd"';
        var x="";
        var y="";
        var tmpPage = 0;
        var companyPhone =""; 
                
        if (Page < g_endPage) 
        {
            tmpPage= Page +1;
            $get('indRight3').innerHTML = "<a href='javascript:ListByPageNo("+tmpPage+")'>Next</a>";
         //   $get('indRightb3').innerHTML = "<a href='javascript:ListByPageNo("+tmpPage+")'>Next</a>";
        }
        else 
        {
            if (g_endPage==1) 
                {$get('indRight2').innerHTML ="";
                // $get('indRightb2').innerHTML ="";
                $get('indRight3').innerHTML ="";
              //  $get('indRightb3').innerHTML ="";
            }
            else        
            {$get('indRight3').innerHTML ="Next";
           // $get('indRightb3').innerHTML ="Next";
            }
        }    
        
        if (Page > 1) 
        {
            tmpPage= Page - 1;
            $get('indRight1').innerHTML = "<a href='javascript:ListByPageNo("+tmpPage+")'>Prev</a>";
            //$get('indRightb1').innerHTML = "<a href='javascript:ListByPageNo("+tmpPage+")'>Prev</a>";
        }
        
        else
        {
            if (g_endPage==1) 
            {   $get('indRight2').innerHTML ="";
                // $get('indRightb2').innerHTML ="";
                $get('indRight1').innerHTML ="";
                //$get('indRightb1').innerHTML ="";
            }
            else        
            {
                $get('indRight1').innerHTML ="Prev";
                //$get('indRightb1').innerHTML ="Prev"; 
            }
        }  
        
        if (endPos > rList_tot) endPos = rList_tot;      
        if (Page >= 1) 
        {  
            $get('indLeft1').innerHTML = rList_tot + " locations, displaying " + startPos + " - " + endPos; 
           // $get('indLeftb1').innerHTML = rList_tot + " locations, displaying " + startPos + " - " + endPos; 
        }       
        
        
        dt =  '<table cellspacing="0" id="resultList"><tr><th id="resColId">ID</th>'+
              '<th id="resColType">Type</th>' +
              '<th id="resColName">Name</th>' +
              '<th id="resColAddress">Address</th>' +
              '<th id="resColPhone">Phone</th>' +
              '<th id="resColDistance">Distance</th></tr>' 

                
        for (var mc=startPos;mc<=endPos;mc++) 
        {
            fieldL = rList_strVal[mc].split("***");
            
            strDest = fieldL[1]+'|'+fieldL[2]+'|'+fieldL[3];
            strDest = RemoveBadChar(strDest);
            strDest = "'" + strDest+"'";
            x = rList_x[mc];
            y = rList_y[mc];
                       
            dt += '<tr class=' + trClass + ' onclick="javascript:ID2Centre(' + x +',' + y + ')" ' + '>';
            dt += '<td class="listtdptid" valign="middle"><a href="javascript:ID2Centre('+x+',' + y+ ')"><img border="0" title="Click to Zoom" src="images/bluepoint'+ mc.toString() + '.gif"></a></td>';
            dt += '<td class="listtdtype" >'+fieldL[1]+'</td>'; //type
            dt += '<td class="listtdname" >'+fieldL[2]+'</td>'; //name
            dt += '<td class="listtdaddress" >'+fieldL[3]+'</td>'; //address
            
            if (fieldL[5].indexOf('Marshall')>-1) companyPhone = '1300 MARSHALL (1300 6277 4255)';
            else if (fieldL[5].indexOf('Battery World')>-1) companyPhone = '13 17 60';
            else if (fieldL[5].indexOf('Instant Windscreens')>-1) companyPhone = '13 24 44';
            else if (fieldL[5].indexOf('NOVUS Autoglass')>-1) companyPhone = '13 22 34';
            else if (fieldL[5].indexOf('Obrien Glass')>-1) companyPhone = '1800 645 011';
            else companyPhone = fieldL[4];
             
            dt += '<td class="listtdphone">'+companyPhone+'</td>'; 
            dt += '<td class="listtddistance">'+rList_Dist[mc]+' km</td>';             
            dt += '</tr>';
            
            if (trColour == '"#f1f1f1"') trColour = '"#ffffff"';
            else if (trColour == '"#ffffff"') trColour = '"#f1f1f1"';
            
            if (trClass == '"even"') trClass = '"odd"';
            else if (trClass == '"odd"') trClass = '"even"';   
            
        }
        dt += '</table>';
        $get('rlist').innerHTML = dt;
        SetPageVisible(_PageStatus.MapPage);
}

function ID2Centre(x,y)
{
    _map.ZoomToPoint(y,x,16);
}

function SetPageStatus(id)
{
    PageStatus = id;
}

function SetPageVisible(PageType)
{
    
    if (PageType == _PageStatus.MapPage) 
    {
        $get('cboLoc').style.display='none';
        $get('mapFrame').style.display='';
        $get('errorMsg').style.display='none';    
  
    }
    else if (PageType == _PageStatus.OnLoadMap)
    {
        //_map.attachEvent("onendzoom",MapMove);
        //_map.attachEvent("onendpan",MapMove); 
        $get('cboLoc').style.display='none';
        $get('mapFrame').style.display='none';
        $get('errorMsg').style.display='none';
        $get('VehicleTitle').style.display ='none';
        $get('makeChooser').style.display ='none';
        $get('selManufac').style.display ='none';
        $get('BrandTitle').style.display ='none';
        $get('tyreChooser').style.display ='none';
        $get('selBrand').style.display ='none';
        $get('copyright').style.display=''; //show copyright at bottom of search   
        $get('fuelChooser').style.display ='none';
        
        $get('radPredealers').checked = false;
        $get('radWindscreen').checked = false;
        $get('radRepairs').checked = false;
        $get('radCaltex').checked = false;
        $get('radTyres').checked = false;
        $get('radBatteries').checked = false;
        $get('selState').value = '';
        $get('txtSuburb').value = '';
    }

}

function BuildOption()
{
    var option = "";
    
    if ($get(_RadioSel.Predealers).checked) 
    {
        option = _RadioSel.Predealers;
    }
    if ($get(_RadioSel.Windscreen).checked) option = _RadioSel.Windscreen; 
    if ($get(_RadioSel.Repairs).checked) option = _RadioSel.Repairs;
    if ($get(_RadioSel.Caltex).checked) option = _RadioSel.Caltex; 
    if ($get(_RadioSel.Tyres).checked) option = _RadioSel.Tyres;
    if ($get(_RadioSel.Batteries).checked) option = _RadioSel.Batteries; 
    return option
}

function BackToResultPage()
{
    SetPageVisible('ListPage');
}

function reset_select()
{
 _map.detachEvent("onendzoom",MapMove);
 _map.detachEvent("onendpan",MapMove);
 SetPageVisible(_PageStatus.OnLoadMap)
}

function DisplayProcessingInfo()
{
    $get('errorMsg').style.visibility='visible';
    $get('errorMsg').innerHTML="Processing your request.";
   

}

function UndisplayProcessingInfo()
{
    $get('errorMsg').style.visibility='hidden';
}

function printWin()
{
    window.print();
}

function RemoveBadChar(src)
{
    return src.replace(/'/, "");
}

function txtBusinessNameEnterKey(e)
{
    var pK = document.all? window.event.keyCode:e.which; //IE:Firefox
    if (pK == 13) SearchClickBody();
    else
    {
        LastInputTown = '';
        $get('DropDownListState').value = '0';
        $get('DropDownListRegion').value = '0';
        $get('errorMsg').style.visibility='hidden';
        $get('multiples').style.visibility='hidden';
        
    }
}
function txtSuburbEnterKey(e)
{
    var pK = document.all? window.event.keyCode:e.which; //IE:Firefox
    if (pK == 13) SearchClickBody();
}

function CleanupArray()
{
    rList_strVal = new Array();
    rList_x = new Array();
    rList_y = new Array();
}

function SearchRadioClick(id)
{
 if (_RadioSel.Predealers == id)
 { 
    $get('BrandTitle').style.display ='none';
    $get('tyreChooser').style.display ='none';
    $get('selBrand').style.display ='none';
    $get('fuelChooser').style.display = 'none';
    GeneralSearch.SetDropdownList($get('UserID').value,'dealer',SetDropdownCallBack);
    $get('selResultNo').selectedIndex = 0;   
 }
 else 
 {
    $get('selResultNo').selectedIndex = 1;
    if (_RadioSel.Repairs == id)
    { 
        $get('BrandTitle').style.display ='none';
        $get('tyreChooser').style.display ='none';
        $get('fuelChooser').style.display = 'none';
        $get('selBrand').style.display ='none';
        GeneralSearch.SetDropdownList($get('UserID').value,'repairer',SetDropdownCallBack);
    }
    else
    {
        if (_RadioSel.Tyres == id)
        { 
            $get('VehicleTitle').style.display ='none';
            $get('makeChooser').style.display ='none';
            $get('selManufac').style.display ='none';
            $get('fuelChooser').style.display = 'none';
            $get('BrandTitle').style.display ='';
            $get('tyreChooser').style.display='';
            $get('selBrand').style.display ='';
        }
        else if (_RadioSel.Caltex == id)
        {
            //Fuel Types
        $get('makeChooser').style.display ='none';
        $get('BrandTitle').style.display ='none';
        $get('tyreChooser').style.display ='none';
        $get('fuelChooser').style.display = '';
        $get('selBrand').style.display ='none';    
        }
        else
        {
            $get('VehicleTitle').style.display ='none';
            $get('makeChooser').style.display ='none';
            $get('selManufac').style.display ='none';
            $get('BrandTitle').style.display ='none';
            $get('tyreChooser').style.display='none';
            $get('selBrand').style.display ='none';
            $get('fuelChooser').style.display = 'none';
        }
     }
 }        
}

function SetDropdownCallBack(results)
{    
    var cboLoc = $get('selManufac');   
    if (results.length>0)
    {
        $get('VehicleTitle').style.display ='';
        $get('makeChooser').style.display ='';
          
        cboLoc.style.display ='';
         
        cboLoc.options.length=0;
        cboLoc.options.length=results.length-1;
        cboLoc[0]=new Option("Please select a Manufacturer","0");            
        for(var a=0;a<results.length;a++) //populate the combobox with locations
        {
            var obj=new Option(results[a],results[a]);
            cboLoc[a+1]=obj;
        }
   }    
}
