/*
all_specials.js
functions for Specials/Coupons
*/


// arrDisplayedGreenGarages array contains all RG and R garages that displayed in
// the current area. The array was filled in listGarages [garagesX.js]
var arrDisplayedGreenGarages = new Array();

var arrSpecialsDescriptions = new Array("", "EARLY-BIRD Specials", "MID-DAY Specials", "EVENING-NIGHT Specials"); 


/* *********************
  LoadXML_AllSpecs
********************* */
function LoadXML_AllSpecs(oDate, load_type)
{ // the function set URL and require XML to download
  // called from:
  // (1) listGarages[garagesX.js] , to load all specials(coupons) 
  //     and coup group for the current area
  // (2) checkShowMonth [r_rg_functions.js], when month data needed to
  //     display month
  // (3) SelectCSdate by clicking calendar date if all cpecs don't happen
  //     to be loaded (LoadingAllSpecs == 0), not normal situation
  
  var centreBounds = gMap.getBounds();
  var bounds = new GLatLngBounds(new GLatLng(centreBounds.getSouthWest().lat() - AREA_CACHE_BORDER/671,
                                            centreBounds.getSouthWest().lng() - AREA_CACHE_BORDER/571),
                                 new GLatLng(centreBounds.getNorthEast().lat() + AREA_CACHE_BORDER/671,
                                            centreBounds.getNorthEast().lng() + AREA_CACHE_BORDER/571));
  
 
  var url = XML_ALLSPECIALS_URL + "?area=" + bounds.getSouthWest().lng() + "," + bounds.getSouthWest().lat() + "," + bounds.getNorthEast().lng() + "," + bounds.getNorthEast().lat()
    + "&mon=" + oDate.getFullYear() + "-" + oDate.getMonth();
  if(load_type) url += "&type=" + load_type;
  
    
  LoadingAllSpecs = -1; // all spec loading
  //alert(url);

  var xmlDoc = getXML(url, doneAllSpecs, 1);

}

/* *********************
      doneAllSpecs
********************* */
function doneAllSpecs(xmlDoc)
{ // XML callback function of All Specials
        
         if(xmlDoc == null || xmlDoc.xml == "")
         {
           alert("Could not retrieve All Specilas at this time.");
           //document.getElementById("coupwait").style.display='none';
           DisplayElem("coupwait", "none");
           return;
         }
      // parse and save all XML document with parseXML_AllSpecs [r_rg_functions.js]
       var params = parseXML_AllSpecs(xmlDoc.documentElement);  
       var load_type = params[0];
       
       LoadingAllSpecs = 1; // all spec loaded for the current map area
        
       // if popups displayed
       if(lastSelectedGarage)RefreshSpec(lastSelectedGarage); // [r_rg_functions.js]
       //DisplayCoups();
       
       DisplayElem("detwait", "none");
       DisplayElem("coupwait", "none");
       
       // not display for Monthly or the map hidden
       if(
       parking_isMonthly ||
       document.getElementById("search_results").style.display=="none"
       )return;
       

       if(!params[2])
       {  // area doesn't contain spec for CS
       MinimizeCoups();
       //document.getElementById("day_sp_min").style.display = "none";
       DisplayElem("day_sp_min", "none");
       }
       else
       {
       //refresh DS content
       //if(!DisplayCoups())
       if(typeof(PopulateDailyExpWin)=="function")
       { 
       if(!PopulateDailyExpWin()) /* bug place */
       DisplayElem("day_sp_min", "none");
       }
       else
       DisplayElem("day_sp_min", "block");
       
       if(load_type == 2) PopulateCal(params[1]); // refresh calendar, as data requested to it      
       }
                    
}


/* *********************
    parseXML_AllSpecs
********************* */

function parseXML_AllSpecs(xmlElem)
{ // called from two places: 
  //  (1) doneFetchGaragesAroundBounds[garages9b.js ] , main garage data parsing
  //  (2) doneAllSpecs[cs_windowX.js], parsing All Specials                                 
  //  parse XML document of All Specials
  // XML output by (1)xmlgaragesX.php , (2) xmlallspecials.php
               
        var areaContainCS = false; 
               
        var xmlGeneral = xmlElem.getElementsByTagName("General")[0];
        
        // month the document contains info on  
        var month = xmlGeneral.getAttribute("month"); 
        var month_indx = month.replace("-", "");
        
        var load_type = xmlGeneral.getAttribute("type");  
        // type 0 - content of 1 type (but for the one day and exclusions applyed), appended to xmlgaragesX.php
        // type 1 - all spec & coup loaded,
        // type 2 - Month Exclusions
        // type 3 - the both
       
        var xmlCoupGroups = xmlElem.getElementsByTagName("CoupGroup"); 

        // get Coupon Groups
        for(c=0 ; c < xmlCoupGroups.length; c++)
        {        
        areaContainCS = true;
        
        var xmlCoup = xmlCoupGroups[c];
        
        var oCoupGroup = new CoupGroup();
        
        oCoupGroup.id = xmlCoup.getAttribute("id");
        oCoupGroup.rate = xmlCoup.getAttribute("rate");
        oCoupGroup.rateSUV = xmlCoup.getAttribute("rateSUV");
        oCoupGroup.description = xmlCoup.getAttribute("description");
        
        if(xmlCoup.getAttribute("description_abbr"))
        oCoupGroup.description_abbr = xmlCoup.getAttribute("description_abbr");
        
        oCoupGroup.link = xmlCoup.getAttribute("link");
        oCoupGroup.garages = xmlCoup.getAttribute("garages");
        
        arrAllCoupGroups[oCoupGroup.id] = oCoupGroup; // add to global array
        }
        
        var xmlGarages = xmlElem.getElementsByTagName("Garage"); 
       
     //// go through all garages  
     for(g=0 ; g < xmlGarages.length; g++)
     {
        var xmlGar = xmlGarages[g];
        var gar_id = xmlGar.getAttribute("id");
      
       //// initialize arrays
      
      if(!garages[gar_id].arrSpecialsMonth[month_indx]) 
      garages[gar_id].arrSpecialsMonth[month_indx] = new Array(); 
       
      if(!garages[gar_id].arrSpecialsMonth[month_indx][1]) 
      garages[gar_id].arrSpecialsMonth[month_indx][1] = new Array(); 
      
      
      if(!garages[gar_id].arrCouponsMonth[month_indx]) 
      garages[gar_id].arrCouponsMonth[month_indx] = new Array(); 
       
      if(!garages[gar_id].arrCouponsMonth[month_indx][1]) 
      garages[gar_id].arrCouponsMonth[month_indx][1] = new Array();      
       
       
      //// month strings
      if(xmlGar.getAttribute("specialsmonth"))
      {
      // add to garage's arrays
      garages[gar_id].arrSpecialsMonth[month_indx][0] = 
      xmlGar.getAttribute("specialsmonth"); 

      garages[gar_id].arrCouponsMonth[month_indx][0] = 
      xmlGar.getAttribute("couponsmonth");
      
      }


         ///// type 2 (Month Exclusions)
         // that are specials(coupons) IDs that excluded from displaying by SYP check 
        if(load_type == 2 || load_type == 3)
        {
        areaContainCS = true;
        
        var xmlExclusions = xmlGarages[g].getElementsByTagName("Exclusion"); 
        
        for(e=0; e < xmlExclusions.length; e++)
        {
        var type = xmlExclusions[e].getAttribute("type"); // spec or coup 
        var day = xmlExclusions[e].getAttribute("day"); // day of defined month in month var
        var specs = xmlExclusions[e].getAttribute("specs");
       
       
        if(type == "s")
        {
        garages[gar_id].arrSpecialsMonth[month_indx][1][day] = specs;
        }
        else  if(type == "c")
        {
        garages[gar_id].arrCouponsMonth[month_indx][1][day] = specs;
        }
        
        }
      
        }
        // end type 2 (Exclusion)
        
        ///// TYPE 1  GET ALL SPECIALS AND COUPONS
        if(load_type == 0 || load_type == 1 || load_type == 3)  // type 1
        {
        
        var xmlWeekdays = xmlGarages[g].getElementsByTagName("Weekday"); 
        
        // go through ALL weekdays
        for(w=0; w < xmlWeekdays.length; w++)
        {
        
        areaContainCS = true;
        
        var wday = xmlWeekdays[w].getAttribute("day");
        
        // go through all Items
        // each Item represents a spec (coupon) for the current garage, weekday
        var xmlSpecials = xmlWeekdays[w].getElementsByTagName("Item");
        
        var arr_coups = new Array();
        var arr_specs = new Array();
        
             for(s=0; s < xmlSpecials.length; s++)
             {
                     // parse a special Item 
             oSpec = parseXMLSpecial(xmlSpecials[s]);
             
             if(oSpec.type == "c")
               arr_coups[arr_coups.length] = oSpec;
             else if(oSpec.type == "s")
               arr_specs[arr_specs.length] = oSpec;
             
             }
        // add to garage's arrays
        garages[gar_id].arrAllCoupNew[wday] =  arr_coups;
        garages[gar_id].arrAllSpecNew[wday] =  arr_specs;
        
        if(load_type>0)garages[gar_id].spclsLoaded = 1;
        
        }
        
        } // end type 1
        
        }  // END Garages
        /*
        var xmlTimer = xmlElem.getElementsByTagName("Timer")[0]; 
        var time =  xmlTimer.getAttribute("time");
        
        document.getElementById("timer").innerHTML +=
        document.getElementById("timer").innerHTML + 
        "<br>C & S: PHP: " +  time + "s";
        */
// the function returns parameters to let know what to do with C & S window:
// load_type - 1,2,3 load type
// month  - month string for calendar
// areaContainCS  true if specs or coups for the area exist


return Array(load_type, month, areaContainCS);
}


/* *********************
    parseXMLSpecial
********************* */
function parseXMLSpecial(xmlSpecial)
{  // parse XML Special element (used for both Special and Coupon)
   // called from parseXML_AllSpecs 
   
     // Special object
     var oSpec = new Special();

     oSpec.id = xmlSpecial.getAttribute("id"); 
     
     if(xmlSpecial.getAttribute("type"))
     oSpec.type = xmlSpecial.getAttribute("type"); 
     
     if(xmlSpecial.getAttribute("show"))
     oSpec.show = xmlSpecial.getAttribute("show");
    
     if(xmlSpecial.getAttribute("description")) 
     oSpec.description  = xmlSpecial.getAttribute("description");
     
     if(xmlSpecial.getAttribute("description_abbr")) 
     oSpec.description_abbr  = xmlSpecial.getAttribute("description_abbr");
      
     
     if(oSpec.type == "c")
     oSpec.rules  = xmlSpecial.getAttribute("rules"); 
     
     oSpec.carr  = xmlSpecial.getAttribute("carr"); 
     oSpec.clarr  = xmlSpecial.getAttribute("clarr"); 
var cdep = oSpec.cdep  = xmlSpecial.getAttribute("cdep");
     oSpec.stay = xmlSpecial.getAttribute("stay");
     var sty = xmlSpecial.getAttribute("sty");
     
     oSpec.NoStay = (sty.charCodeAt(0) == 8212); 
      
     oSpec.rate = xmlSpecial.getAttribute("rate");
     oSpec.rateSUV = xmlSpecial.getAttribute("rateSUV");
      
      
var dep = oSpec.dep = xmlSpecial.getAttribute("dep"); 
var depEarl = xmlSpecial.getAttribute("depEarl"); 
   
    // head for specials: (1)Depart by (no "Earliest Dep."), 
    //                    (2)Depart (both earliest dep. and latest dep. entries)
    //                    (3)Depart after (only an earliest dep ), 
                             
    var str_dep = dep;
    
   
   
    if(!POP_SPEC_FULL && oSpec.type == "s")
    {
    if(depEarl == "&#8212;")
    {oSpec.headDep = 'Depart&nbsp;by'; str_dep = dep;}
    else if(dep == "&#8212;")
    {oSpec.headDep = 'Depart<br>after'; str_dep = depEarl;}
    else
    {oSpec.headDep = 'Depart';  str_dep = depEarl + "-" + dep;}
    }
   
    if(POP_SPEC_FULL && oSpec.type == "s")str_dep = depEarl + '</td><td>' + dep;
   
    oSpec.specStr = 
    "<nobr>" + xmlSpecial.getAttribute("arr") + "</nobr>" +
    "</td><td>" + str_dep +
    "</td><td><center>"  + sty +
    "</center></td>"; 

    if(xmlSpecial.getAttribute("redir")) 
     oSpec.redir  = xmlSpecial.getAttribute("redir");
    
    // returns Special object
    return oSpec;
 }



/* *********************
    selectSpecsShow
********************* */
function selectSpecsShow(arrSpecs, spec_type, gar, indx, day, show, bGarIsSpec)
{  // in short, the function checks specs(coups) against exclusions
   // called from garage's getDetailHTML [garagesX.js]
   // indx - month index (format "YYYMM") , current date
   // day  - day of month                 , current date
   // show - if set, select this
   
   // alert("selectSpecsShow " + show);
    
   ////////////////////////////////////////////////////////////////
   /// Specials Map View:
   // if called from getDetailHTML and bGarIsSpec set to true
   // then it means it's Specials Map View so
   // main Spec/Coup wil be excluded from returned Specials and set to 
   // oSVSp

   //alert(bGarIsSpec);
   
   if(bGarIsSpec)
   {
   //alert("gar.spec_view " + gar.spec_view);

   var sv_arr = gar.spec_view.split(" ");
   var sv_type = sv_arr[0]; // "cg" (coup group), "s" (spec) or "c" (coup)
   var sv_id = sv_arr[1];  // id for cg or index in garages[garid].arrAllSpecNew[<weekday>]
    
   } 
   ////// END Specials Map View 
    
    var arrReturnSpecs = new Array();
    var i = 0;
    
    var loc_spec_excl = ""; // get exclusions for that date
    // get exclusions
    if(spec_type == "s")
    loc_spec_excl = gar.arrSpecialsMonth[indx][1][day];
    else if(spec_type == "c")
    loc_spec_excl = gar.arrCouponsMonth[indx][1][day];
    
    if(loc_spec_excl == null)loc_spec_excl = "";

     
    // look every cpec(coup) ID in exclusions string
    for(var n = 0; n < arrSpecs.length; n++)
    {
    // if exists do not display this spec(coup)
    if(loc_spec_excl.indexOf(" " + arrSpecs[n].id + " ") > -1)continue;    
    
    /// Spec Map View
   /* if(bGarIsSpec && sv_type == spec_type && sv_id == n)
    {
    gar.oSVSp = arrSpecs[n];
    continue;
    } */
    /*
    alert("selectSpecsByShow: " + arrSpecs[n].rate +  " - " + 
    arrSpecs[n].description + " - " + arrSpecs[n].show);         
    */

    if(show==2 && trim(arrSpecs[n].description)== "")continue;
    
    //if(arrSpecs[n].show == show || arrSpecs[n].show == 3)
    // currently no difference between 1 and 2
    if(arrSpecs[n].show > 0)
    arrReturnSpecs[n] = arrSpecs[n];    

    
    }

return arrReturnSpecs;
}


