/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        r_rg_functions.js
RG & R (green) system  functions

v.12u  version for Custom compatibility
v.21m  versions (get variable)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */

var arrAllCoupGroups = new Array(); // all Coupon Groups
var LoadingAllSpecs = 0;

///// Special object
function Special()
{ // the object keeps info on a special(coupon)
this.id = null; // spec(coup) ID 
this.type = 0; // 's' (special) or 'c' (coupon)
this.show = null; // show spec(coup) in (show==1)map popup, (show==2)C & S , (show==3) both
this.description = "";
this.description_abbr = ""; 
this.carr  = null;  //carr: seconds from day start
this.clarr  = null; //clarr: seconds from carr
this.cdep  = null;  //cdep: seconds from cdep 
this.stay = null;  
this.dep = null;
this.headDep = 'Depart by'; // Depart by, Depart after, Depart
this.rate = ""; 
this.rateSUV = "";
this.specStr = "";
this.redir = 0; // redirect (coupons)
}
///// CoupGroup object
function CoupGroup()
{
this.id = null;
this.rate = null;
this.rateSUV = null;
this.description = "";
this.description_abbr = "";
this.link = "";
this.garages = ""; // related garages IDs
}

///// SpecMonth
function SpecMonth()
{ // not in use
this.strCal = "";
this.arrExcl = new Array();
}


/* *********************
   HideGreenDetailsStub
********************* */
function HideGreenDetailsStub(evnt)
{ // called from clicking 'map_green_detail_label' and 'list_detail_label'
  // the meaning of the function is that the popups closed by cllicking them,
  // and they should not be closed while clicking input button, select of some other areas
 
//if(globJSBrowser == "" || globJSBrowser == "Safari")return;
  
  if(globJSBrowser == "IE" || globJSBrowser == "Safari")
  var oSource = window.event.srcElement; // object that clicked
  else if(globJSBrowser == "Firefox")
  var oSource = evnt.target;
   
var targetTag = oSource.tagName.toLowerCase();
 
if(targetTag == "input" || targetTag == "td" || targetTag == "select" || oSource.id == "godiv" || targetTag == "option" || targetTag == "a")return;

HideGreenDetails();

}


var lastHourFld = null;
var lastSpclCoup = null;


//// OpenGetGuarantee
//  << Get RG/R system: >>
function OpenGetGuarantee(swp_num, garid, SpclCoup)
{
// called when 'Get Free RG' (R) button on the map or list popup 
// - next to search result, special(coupon) - clicked
//
// swp_num - index of spec(coup) in arrAllSpec[<weekday>] array, '-1' for search
// green - green type: 1 ('RG') or 2 ('R') and 3,4 for search
// SpclCoup - string, the one of 'c', 's', 'cl', 'sl' , where c - coupons, s - specials, l - list popup ; optional

//alert("OpenGetGuarantee: swp_num: " + swp_num + "  garid: " + garid + "  SpclCoup: " + SpclCoup);
//return;
 
var loc_2nd = SpclCoup.substr(1,1);


var strCom = new String(garages[garid].company);
   
if(swp_num > -1) // spec or coup, not search
{    
     var loc_SC = SpclCoup.substr(0,1);
    
     if(loc_SC == "c") // coupon : never pop hour - no need in asking Arrival
     {  
         if(strCom.toLowerCase() == "icon" && garages[garid].dps2nd)
          {DisplayPopHour(garid, SpclCoup, swp_num);return;}
         else  
          {GoCoupon(garid, SpclCoup, swp_num, 2);return;}
     }     
     else if(strCom.toLowerCase() == "icon" && garages[garid].green==2)
     {     
         DisplayPopHour(garid, SpclCoup, swp_num);return;
     }
     else /*if(strCom.toLowerCase() == "edison" || strCom.toLowerCase() == "five star")*/
     { // check  type of Discount 
          
         
         if(loc_2nd == "w") 
          var loc_wd = currDSwindowDate.getDay(); 
         else
          var loc_wd = currSpclsDate.getDay();
          
          if(loc_SC == "s")
          var loc_specs = garages[garid].arrAllSpecNew[loc_wd][swp_num];
          else if(loc_SC == "c")
          var loc_specs = garages[garid].arrAllCoupNew[loc_wd][swp_num]; 
          
          //alert(loc_specs.NoStay);
          
          if(loc_specs.NoStay || parseInt(loc_specs.stay) < 0)
          {
          GoCoupon(garid, SpclCoup, swp_num, 2);return;
          }
          else
          {
          DisplayPopHour(garid, SpclCoup, swp_num);return;
          }
          
     }

} // 

/// if swp_num == -1, from search, other returned earlier

var isRedir = (strCom.match(/Icon/i) && (garages[garid].green==2));

if(parking_arrival == null)
var arr = getGMTTime(new Date())/1000;
else
{
var arr = getGMTTime(parking_arrival)/1000;
var dep = getGMTTime(parking_departure)/1000;
var veh = parking_vehicle;
}

var isSRedir = garages[garid].sredir;  // redirection from Search area

/// Advanced search 
if(garages[garid].green==0 || isSRedir) /* SDerir only to GET_RATE_SUMMARY_URL*/
{
URL = GET_RATE_SUMMARY_URL;
}
else
{
if(isRedir)
URL = GET_RESERV_ADVANCE_URL; //"advanced_search.php";
else
URL = GET_GUARANT_ADVANCE_URL;
}

URL += "?v=" + VERSION + "&id=" + garid + "&arr=" + arr + "&dep=" + dep + "&veh=" + veh + "&t=srch";

if(isRedir)URL += "&redir";
if(isSRedir)URL += "&sredir";
//alert(URL);
  
  
  
HideGreenDetails(); // hide all popups

if(isRedir)
oPopWin = window.open(URL,"","width=530,height=550,resizable=1 ,toolbar=0, location=0, status=0, menubar=0, directories=0, scrollbars=0");
else if(isSRedir) // Search Redir
oPopWin = window.open(URL, "", "");
else                              //480
oPopWin = window.open(URL,"","width=480,height=550,resizable=1 ,toolbar=0, location=0, status=0, menubar=0, directories=0, scrollbars=0");

if(isSRedir)
SendTracker('/search_redirected');

}

//// DisplayPopHour
//  << Get RG/R system: >>
function DisplayPopHour(garid, SpclCoup, swp_num)
{
// displays Hour-Go-Cancel inputs in place of 'Get Free RG(R)' button
// SpclCoup - see OpenGetGuarantee function
// swp_num -  see OpenGetGuarantee

    //alert("DisplayPopHour " + SpclCoup + " " + swp_num);
     
    // var garid = lastSelectedGarage.licenceNumber;
     
     var loc_SC = SpclCoup.substr(0,1); // 1st letter, 'c' or 's'
     var loc_2nd = SpclCoup.substr(1,1); // 
     var fromCSwin = loc_2nd == "w";
     var addW = "";

    // closes other if displayed
    //if(!fromCSwin)
    GoClose(); 
     
     if(fromCSwin)
     {
     var currWD = currDSwindowDate.getDay();
     var addW = "w";     
     }
     else
     {
     var currWD = currSpclsDate.getDay();     
     }

     
     if(loc_SC == "s")
     var loc_specs = garages[garid].arrAllSpecNew[currWD][swp_num];
     else if(loc_SC == "c")
     var loc_specs = garages[garid].arrAllCoupNew[currWD][swp_num];     
     
     
    // parse arrival to set in Hour fields
    if(loc_SC == "c" && parking_isCase)
    var loc_arr_m = (parking_arrival.getHours()*60) + parking_arrival.getMinutes(); 
    else
    var loc_arr_m = loc_specs.carr/60;
     
    var hours = Math.floor(loc_arr_m/60);
    var min =   Math.floor(loc_arr_m%60);  
    var PM = 0;
    if(hours>11){hours -= 12; PM = 1;}
     

    var content = '<table class="cont plain" cellspacing="0" width="100%"><tr><td>';
     
     
     // Hours field
     content += 
          '<center style="/*border:1px solid #000;*/"><select class="cal ys" name="arrHours' + swp_num  + addW + '" >'
          + '<option value="" selected style="background:#ffff55;">hr</option>';
          
          for(var h = 0; h < 12; h++)
          {
          content += '<option value="' + h + '" ';
          if(h == hours)content += 'selected';
          content += '>';
          if(h == 0)content += '12';
          else content += h;
          content += '</option>';   
          }
          
          
      content += '</select>&nbsp;';
      
      // Minutes field  
      content += '<select  class="cal" name="arrMinutes' + swp_num  +  addW + '" >';
                          
          for(var m = 0; m < 60; m += 5)
          {
          content += '<option value="' + m + '" ';
          if(m == min)content += 'selected';
          content += '>';
          if(m == 0 || m == 5)content += '0';
          content += m + '</option>';   
          }
          
      content += '</select>'; 
        
        // AM / PM field  
        content += '<input type="radio" name="arrAMPM' + swp_num  +  addW + '" value="0" ';
        if(!PM)content +=  'checked';
        content += '>AM';
        content += '<input type="radio" name="arrAMPM' + swp_num  +  addW + '" value="12" ';
        if(PM)content +=  'checked';
        content += '>PM';
        
        
        content += '</td></tr><tr><td style="padding-top:2px; background:#033859;">';
          
       content += '<center><table class="plain" cellspacing="0" style=""><tr><td>';
       
       content +=   
       '<div class="mb_btn" onClick="GoCoupon( ' + garid  + ' ,\'' + SpclCoup +'\', ' + swp_num  + ');" style="width:35px;">' +
       '<div class="c"><div class="l"><div class="r">' +
       'Go' +
       '</div></div></div></div>';
       
       content += '</td><td>&nbsp;</td><td>';
       
       content +=   
       '<div class="mb_btn" onClick="GoClose();" style="width:55px;">' +
       '<div class="c"><div class="l"><div class="r">' +
       'Close' +
       '</div></div></div></div>';    
          
       content += '</td></tr></table>';   
                    
        
        content += '</td></tr></table></center>';

        
// set position of the Hours-Go-Cancel 
//var row = document.getElementById(SpclCoup + swp_num);
 
arr_pos = getAbsolutePositionOf(document.getElementById(SpclCoup + swp_num));


var row = GetElement('pophour'); 
GetElement('pophourtd').innerHTML = content; 

row.style.left = (parseInt(arr_pos[0]) + 8);
row.style.top = parseInt(arr_pos[1]);
DisplayElem('pophour', 'block');


var instruct = document.getElementById("flick6"); 

var addW = 0;
if(globJSBrowser != "IE")addW = 4; 

instruct.style.width = parseInt(row.offsetWidth) - addW; //  + 
instruct.style.display = "block";
instruct.style.left = (parseInt(arr_pos[0]) + 8);
instruct.style.top = (arr_pos[1] - 26); /* 22 */


lastHourFld = swp_num;
lastSpclCoup = SpclCoup;

}

//// GoClose
//  << Get RG/R system: >>
function GoClose()
{
// on click Cancel button
// hides Hour fields, Go and Cancel buttons and display 'Ger Free RG(R)'  button
  
   GetElement('pophourtd').innerHTML = '';
   DisplayElem('pophour', 'none');
   DisplayElem("flick6", "none");


}

//// GoCoupon 
//  << Get RG/R system: >>
function GoCoupon(garid, SpclCoup, swp_num, type)
{
// called by 'Go' button clicked or directly from OpenGetGuarantee (click Get Free RG(R) button) 
// SpclCoup - see OpenGetGuarantee function (index.php)
// swp_num -  see OpenGetGuarantee
// type == 2 - arrival is not from hours input, but OpenGetGuarantee

//alert("GoCoupon " + swp_num);

/// Coupon Descriptions (new Coupons)

if(SpclCoup == "cd") 
{

if(type) // type==1 for 'cd' for fake Coupon
{
var URL = XML_GET_COUPON_URL + '?v=' + VERSION + '&cd=' + 
swp_num + '&arr=' + (getGMTTime(currDSwindowDate)/1000);
oPopWin = window.open(URL,"","width=480,height=550,resizable=1 ,toolbar=0, location=0, status=0, menubar=0, directories=0, scrollbars=0");
}
else
{
var URL = XML_GET_RESERV_URL + '?v=' + VERSION + '&cd=' + 
swp_num + '&arr=' + (getGMTTime(currDSwindowDate)/1000);
oPopWin = window.open(URL, "", "");
}
return;
}


 var loc_SC = SpclCoup.substr(0,1);
 var loc_2nd = SpclCoup.substr(1,1);
 
var strCom = new String(garages[garid].company); 
var comp = strCom.toLowerCase(); 

    if(loc_2nd == "w") 
     var currDate  = currDSwindowDate;  
    else
     var currDate  = currSpclsDate; 
    
    var currWD = currDate.getDay();
    
     if(loc_SC == "s")
     var loc_specs = garages[garid].arrAllSpecNew[currWD][swp_num];
     else if(loc_SC == "c")
     var loc_specs = garages[garid].arrAllCoupNew[currWD][swp_num];    
    
    
    if(loc_2nd == "w")swp_num += "w";  
    

var id = loc_specs.id;
var loc_arr = loc_specs.carr;
var loc_lat_arr = loc_specs.clarr;
var loc_dep = loc_specs.cdep;

//alert("GoCoupon: id" + id + " - " + SpclCoup + " - " + swp_num + " - " + type);

///if(loc_SC == "c")type = 2; // 21s fix (coupon commented in )

if(!type) // get hours from Hour fileds
{
var hours = document.getElementsByName("arrHours" + swp_num)[0].value;

//alert(hours  + " - " + document.getElementById("arrHours"+ swp_num));

if(hours == "")
{
alert("Please enter your arrival time.");
return;
}

var min = document.getElementsByName("arrMinutes" + swp_num)[0].value;

var am = document.getElementsByName("arrAMPM" + swp_num)[0].checked;
var pm = document.getElementsByName("arrAMPM" + swp_num)[1].checked;

if(pm)hours = parseInt(hours) + 12;

var  user_arr = hours*3600 + min*60;

} // end if(!type)
else  
{
var  user_arr =  parseInt(loc_arr);
}

var loc_max_stay = parseInt(user_arr) +  parseFloat(loc_specs.stay)*3600;

var tmp_dep = parseInt(loc_arr) + parseInt(loc_dep);
var tmp_lat_arr= parseInt(loc_arr) + parseInt(loc_lat_arr);


/*
alert(id + " - loc_arr:" + loc_arr + " - loc_lat_arr:" + loc_lat_arr
 + " - loc_dep:" + loc_dep + " - loc_max_stay:" + loc_max_stay);
*/

if(user_arr < loc_arr || user_arr > tmp_lat_arr)
{
if(loc_SC == "s")var add_str = "Special";
else if(loc_SC == "c")var add_str = "Coupon";

alert('ARRIVAL must be within ' + add_str  + '\'s earliest and latest "Arrive" times.');
return;
}

// calculates arr and dep times (time stamps) for URL

var curr_ts = getGMTTime(currDate)/1000;

var arr = parseInt(curr_ts) + parseInt(user_arr);

var tmpDep1 = parseInt(curr_ts) + parseInt(loc_max_stay);

var tmpDep2 = parseInt(curr_ts) + parseInt(tmp_dep);

var dep = Math.min(tmpDep1, tmpDep2);
// 


var spec_id = "";

if(type)
{
if(loc_SC == "s")
spec_id = "&spec=" + id;
}

if(loc_SC == "c")spec_id = "&coup=" + id;

// feature to output Icon print form with 1/2 less departure
var trick = "";
if(loc_SC == "s" && comp == "icon" && garages[garid].green==2)
if(!loc_specs.NoStay)trick = "&trick=" + loc_specs.stay;

//alert("type: " + type + " loc_SC: " + loc_SC + " spec_id" + spec_id);

if(loc_SC == "c") // Coupons
{
if(loc_specs.redir)
{ // to be redirected
var URL =  XML_GET_GUARANT_URL + "?v=" + VERSION + "&id=" + garid + "&arr=" + arr +
"&dep=" + dep + "&veh=1" + spec_id;
}
else
{ // open in BP print form
var URL = XML_GET_COUPON_URL + "?v=" + VERSION + "&id=" + garid + 
spec_id + '&arr=' + (getGMTTime(currSpclsDate)/1000); // problem
}
var isRedir = loc_specs.redir;

}
else if(!type && loc_SC == "s" && comp == "icon" && garages[garid].green==2)
{  // Advanced Search case 
var URL =  GET_RESERV_ADVANCE_URL + "?v=" + VERSION + "&id=" + garid + "&arr=" + arr +
"&dep=" + dep + "&veh=1" + spec_id + trick;
var isRedir = 1;
var isAdvanced = 1;
}
else if(!type && loc_SC == "s") // last fix
{  // Advanced Search case 
var URL =  GET_GUARANT_ADVANCE_URL + "?v=" + VERSION + "&id=" + garid + "&arr=" + arr +
"&dep=" + dep + "&veh=" + parking_vehicle + spec_id;
if(garages[garid].dps2nd)isRedir = 1;
}
else if(type)
{
var URL =  XML_GET_GUARANT_URL + "?v=" + VERSION + "&id=" + garid + "&arr=" + arr + "&veh=" + parking_vehicle + spec_id;
var isRedir = 0;
if(garages[garid].dps2nd)isRedir = 1;
}
else if(!type)
{
var URL =  XML_GET_GUARANT_URL + "?v=" + VERSION + "&id=" + garid + "&arr=" + arr +
"&dep=" + dep + "&veh=" + parking_vehicle;
var isRedir = 0;
}


URL = URL + "&t=" + loc_SC;
if(isRedir)URL += "&redir";

//alert(URL);

if(isAdvanced)                      // 530
oPopWin = window.open(URL,"","width=530,height=550,resizable=1 ,toolbar=0, location=0, status=0, menubar=0, directories=0, scrollbars=0");
else if(isRedir)
oPopWin = window.open(URL, "", "");
else 
oPopWin = window.open(URL,"","width=480,height=550,resizable=1 ,toolbar=0, location=0, status=0, menubar=0, directories=0, scrollbars=0");

}   //  end GoCoupon


/*
////////////////////////////////////
//    updateSpecailCal
// 
function updateSpecailCal()
{
// the function called on clicking calendar day.
var tmp_date = document.getElementById('popDateTemp' + calendPlace).value;
ChangeSpec(tmp_date, calendPlace);
}
*/
////////////////////////////////////
//    InitCal
// to be made before opening calendar that is in popup
function InitCal()
{
GoClose();
calPadding = true;
}

///////////////////////////////////////////////
//    ChangeSpec
// called on clicking calendar day.
// It checks the date (strDate) and refresh popup or starts loading

// function ChangeSpec(strDate, place)
function ChangeSpec()
{ 
var garage = lastSelectedGarage;

/*
var arr_date = strDate.split("-");
var tmpDate = new Date(arr_date[0] , arr_date[1], arr_date[2]);
// new date(strDate) and current one are equal
if(tmpDate.toString() == currSpclsDate.toString())return;
// set new meaning for global date 
currSpclsDate = new Date(arr_date[0] , arr_date[1], arr_date[2]);
*/
// get date from calendar global var
currSpclsDate = dateCalendarDate;
 
if(LoadingAllSpecs == -1)
{
DisplayDetailWait(place);
return;
}

if(garage.spclsLoaded == -1) // not normal situation
{DisplayDetailWait(place); return;}


var loadtype = 0;
var add = "";

var indx = currSpclsDate.getFullYear() + "" +  currSpclsDate.getMonth();//arr_date[0] + "" + arr_date[1] ;

// month data: type 2
if(garage.arrSpecialsMonth[indx] == null
||
garage.arrCouponsMonth[indx] == null
)
{
loadtype = 2;
add = indx;
}

// spec data
if(garage.spclsLoaded == 0)loadtype += 1;

if(loadtype > 0)
{ //  if needed data to download, starts downloading

DisplayDetailWait(place);
LoadXML_AllSpecs(currSpclsDate, loadtype);
//GetGarageSpecials(garage, loadtype, add);
}
else
RefreshSpec(garage);

}

////////////////////////////////
//     RefreshSpec

function RefreshSpec(garage)
{ 
// refresh the detail popups(map and list) contents

if(currSpclsDate == null) return;

//document.getElementById("map_green_detail_label").innerHTML = 
garage.setDetailHTML("map_green_detail_label", true, 2);

if(document.getElementById("list_detail_label"))
garage.setDetailHTML("list_detail_label", true, 3);
//document.getElementById("list_detail_label").innerHTML = 


}

////////////////////////////////
//     checkShowMonth
// the func called when user select new month on calendar

function checkShowMonth(newMonthDate)
{ 
if(calendPlace == 0)return false;

var indx =  newMonthDate.getFullYear() + "" + newMonthDate.getMonth();

//alert("checkShowMonth " + calendPlace);

var bCSMonthLoad = true; 

for(var lg=0; lg < arrDisplayedGreenGarages.length; lg++)
{
if(garages[arrDisplayedGreenGarages[lg]].arrSpecialsMonth.length > 1
&& garages[arrDisplayedGreenGarages[lg]].arrSpecialsMonth[indx] == null)
{bCSMonthLoad = false;break;} 
}

if(!bCSMonthLoad)
{

if(calendPlace == 1) // DS window
//document.getElementById("coupwait").style.display='block';
DisplayElem("coupwait", "block");
else
DisplayDetailWait(calendPlace);

LoadXML_AllSpecs(newMonthDate, 2);

return true; // the calendar month will not be changed (displayed)
}

return false;  

};

/////////////////////////////////
//    DisplayDetailWait
function DisplayDetailWait(place)
{ 
// the alert is displayed above calendar while specs or month data downloading

var tmpPop = document.getElementById("popDateTemp" + place);
var arr_pos = getAbsolutePositionOf(tmpPop);
var detwait = document.getElementById("detwait");
       
detwait.style.left = parseInt(arr_pos[0]);
detwait.style.top = parseInt(arr_pos[1] - 50);

detwait.style.display='block';
}


/* floating DIV that appears in map or C & S detail popup on "Get Free RG (R)" 
in some cases */
document.write(
'<div id="flick6" class="flickon6" style="width:196px;font-size:10pt;display:none;position:absolute;z-index:3010;background:#ffffcc; vertical-align:middle;padding:3px 0px 3px 0px;font-weight:bold;">' +
'<center>Enter Arrival Time & Click Go</center>' +
'</div>'
);

document.write(
'<table id="pophour" class="plain" style="display:none;" cellspacing="0"><tr><td id="pophourtd"></td></tr></table>'
);



