// $Header: /WebSites/affiliate/promotion/lastminutecruises/lastMinutePage.js 25    2/01/10 3:56p Mccusker $

var LMP = new Object();

// Returns the appropriate object for AJAX calls
LMP.getXMLHttpRequest = function() {
  if(window.XMLHttpRequest)
    // If IE7, Mozilla, Safari, and so on: Use native object.
    return new XMLHttpRequest();
  if(window.ActiveXObject)
    // ...otherwise, use the ActiveX control for IE5.x and IE6.
    return new ActiveXObject('MSXML2.XMLHTTP.3.0');
  // not ajax capable
  return null;
}

LMP.log = function(text) {
  if(window.console && window.console.log)
    window.console.log(text);
}// end LMP.log()

// dynamically insert or remove an expand row from the last
// minute deals table
LMP.switchExpand = function(img, shouldExpand, itinId, vessId) {
  try { 
      if(!img) return;
      if(shouldExpand) {    
        var row = document.getElementById(img.id + "Row");
        if(!row) return;
        var divElements = row.getElementsByTagName('div');
        // fill the expand row with the itinerary if it is not already there
        if((itinId != null) && (vessId != null)) {
            var data    = document.createElement("td");    
            var colspan = document.createAttribute("colspan");
            var align   = document.createAttribute("align");
            colspan.value = "8";
            align.value   = "center";
            data.setAttributeNode(colspan);
            data.setAttributeNode(align);
            data.className = "expand";
            row.appendChild(data);
            var pageRequest = LMP.getXMLHttpRequest();   
            if(!pageRequest) return;

            // get the document
            pageRequest.open("GET","/promotion/lastminutecruises/itineraryExpansion.asp?itinId=" + itinId + "&vessId=" + vessId,false);
            pageRequest.setRequestHeader("Content-Type", "text/html");
            pageRequest.send(null);
            if(pageRequest.status != 200) return;
            
            // append the transformed document to the DOM 
            data.innerHTML = pageRequest.responseText;

            var closeBox = document.getElementById('closeBoxId');
            if (closeBox != null) {
                closeBox.setAttribute('id','');
                closeBox.setAttribute('href','javascript:LMP.switchExpand(document.getElementById(\'' + img.id + '\'), false);void(0);');
            }
        }// end if does not have child nodes
        row.style.display = '';
        img.src           = "/images_unique/btn_collapse_b.gif";
        img.onclick       = function(event) { LMP.switchExpand(this,false) };
        // set the 'See Itinerary Details' link to 'Hide Itinerary Details'
        LMP.switchLinkText(img,true);
        return;
      }
  }// end try to switch the expansion
  catch (e) {
    LMP.log('Could not switch the expansion: ' + e);
  }// end catch and log exceptions
  try {
    // remove itinerary row
    var hideNode = document.getElementById(img.id + "Row");
    if(!hideNode) return;
    hideNode.style.display  = 'none';
    img.src                 = "/images_unique/btn_expand_b.gif";
    img.onclick             = function(event) { LMP.switchExpand(this,true) };
    // set the 'See Itinerary Details' link to 'Hide Itinerary Details'
    LMP.switchLinkText(img,false);
  }// end try to remove an itinerary row
  catch(e) {
    LMP.log('Could not remove the itinerary row: ' + e);
  }// end catch and log errors
}// end function LMP.switchExpand()


// changes the text and action of the 'See Itinerary Details' link depending
// on if the itinerary box has been expanded or not
LMP.switchLinkText = function(img,shouldHide) {
  try {
    if(!img) return;
    var itineraryDetails = img.nextSibling;
    while(itineraryDetails && itineraryDetails.nodeType!=1) {
      if(itineraryDetails.tagName && itineraryDetails.tagName.toLowerCase()!='a')
        break;
      itineraryDetails = itineraryDetails.nextSibling;
    }
    if(!itineraryDetails) return;
    var linkText = itineraryDetails.firstChild;
    if(!linkText && !(linkText.nodeValue) && !(linkText.nodeValue.length > 0)) return;
    var findText    = "Hide";
    var replaceText = "See";
    if(shouldHide) {
      findText = "See";
      replaceText = "Hide";
    }
    linkText.nodeValue = linkText.nodeValue.replace(findText,replaceText);
    itineraryDetails.href = "javascript:LMP.switchExpand(document.getElementById('" + img.id +
                            "')," + !shouldHide + ");void(0);"
  }// end try to switch link text
  catch(e){
    LMP.log('Could not switch linked text: ' + e);
  }// end catch and log errors
}// end function LMP.switchLinkText()

LMP.hideLoadingDiv = function() {
  try {
    document.getElementById('loadingDiv').style.display = "none";
  }// end try to hide the Loading... division
  catch(e) {
    LMP.log('Could not hide the Loading division: ' + e);
  }// end catch and log errors hiding the Loading... division
}// end function LMP.hideLoadingDiv()

// sorts the groups in the 'All Last Minute Cruise Deals' section of the
// lastminutecruises.asp page
LMP.sortGroupings = function() {
  try {
    var groupings = document.getElementsByClassName("allCruiseDeal",
                                                    document.getElementById('allDeals'),
                                                    "DIV");
    var allDeals = document.getElementById("allDeals");
    var groupingData = new Array();

    // collect all the links in the groupings
    for(var groupIndex in groupings) {
        var group = groupings[groupIndex];
        if(!group)
            continue;
        var link = group.getElementsByTagName('a');
        if(!link || !(link.length))
            continue;
        link = link[0];
        var span = group.getElementsByTagName('span');
        if(!span || !(span.length))
            continue;
        span = span[0];
        if(!link || !span)
            continue;
        groupingData.push( { a: link, span: span, data: group.innerHTML } );
    }
    if(groupingData.length != groupings.length) {
      LMP.hideLoadingDiv();
      return;
    }

    // Remove entries for empty groups
    var groupAnchors = document.getElementsByClassName("groupAnchor", 
                                                       document.getElementById(
                                                                      "lastMinuteBody"), 
                                                       "a");
    var originalGroupings = groupings.slice(0);
    
    for (var groupDataIndex in groupingData) {
        var isValidGroup = false;
        for (var anchorIndex in groupAnchors) {
            var groupHref = groupingData[groupDataIndex].a.href;
            if(("#" + groupAnchors[anchorIndex].name) == groupHref.substring(
                                                              groupHref.indexOf('#'))) {
                isValidGroup = true;
                break;
            }
        }
        if (isValidGroup == false) {
            groupingData.splice(groupDataIndex, 1);
            groupings.splice(groupDataIndex, 1);
        }
    }
    

    // Remove all the groupings current data
    var originalGroupingsLength = originalGroupings.length
    for(var index=0; index < originalGroupingsLength; ++index) {
        var group = originalGroupings[index];
        group.innerHTML = '';
    }

    // Map the sorted group data to the appropriate location
    var groupingsLength = groupings.length;
    var newRowCount     = Math.ceil(groupingsLength / 3);
    var dataPointIndex  = 0;
    var bottomRowGroup  = null;

    for(var column=0; column < 3; ++column) {   
        for (var row = 0; row < newRowCount; ++row) { 
            var group = originalGroupings[((row*3) + column)];
            if (group) {
                var insertNodes = groupingData[dataPointIndex];
                if (insertNodes) {
                    group.innerHTML = insertNodes.data;
                    ++dataPointIndex;            
                }
            }
        }
    }

    LMP.hideLoadingDiv();
    document.getElementById('groupsDiv').style.display = "block";
    allDeals.style.height = ((newRowCount*20) + 50) + "px";
  }// end try to sort the LMP groupings
  catch(e) {
    LMP.log('Could not sort LMP groupings: ' + e);
    LMP.hideLoadingDiv();
  }// end catch and log exceptions
}// end function LMP.sortGroupings()

if (/lastminutecruises.asp/.test(window.location.toString())) { 
    addEvent(window,"load",LMP.sortGroupings);
}


//Set Bonus Offer images to the appropriate storecode-based version
LMP.setBonusImages = function(){
    var imageSrc = "";
    var location = window.location.toString();
    if ( /cruisesonly.com/.test(location) ) {
        imageSrc = "/images_unique/cr/bonus_offer_j.gif";
    }
    else if ( /cruises.com/.test(location) ) {
        imageSrc = "/images_unique/cr/bonus_offer_w.gif"; 
    }
    else if ( /cruise411.com/.test(location) ) {
        imageSrc = "/images_unique/cr/bonus_offer_k.gif";
    }
    else if ( /vacationoutlet.com/.test(location) ) {
        imageSrc = "/images_unique/cr/bonus_offer_v.gif";
    }
    else if ( /cruiseoutlet.com/.test(location) ) {
        imageSrc = "/images_unique/cr/bonus_offer_v.gif";
    }

    var bonusOffers = document.getElementsByClassName('bonus_offer', document.getElementById('lastMinuteBody'), 'IMG');            
    for (var offer in bonusOffers) {
        bonusOffers[offer].src = imageSrc;
    }
}
    
addEvent(window, "load", LMP.setBonusImages);

