// POP UP
// usage: popuplink(['js-only url',] this[, w[, h[, scroll[, extras]]]])
// basic usage: <a href="popup.html" target="_blank" onclick="return(popuplink(this));">new pop</a>
// advanced usage: <a href="popup_nojs.html" target="_blank" onclick="return(popuplink('popup_yesjs.html', this, 200, 100, false));">new pop</a>
// site-wide defaults:
POPUP_W = 400;
POPUP_H = 300;
POPUP_SCROLL = true;
POPUP_EXTRAS = 'location=0,statusbar=0,menubar=0';
function popuplink() {
	var undef, i=0, args=popuplink.arguments;
	var url = (typeof(args[i])=='string') ? args[i++] : args[i].getAttribute('href');
	var target = args[i++].getAttribute('target') || '_blank';
	var w = args[i++];
	var h = args[i++];
	var s = (args[i]===undef) ? POPUP_SCROLL : args[i++];
	var features = 'width=' + (w || POPUP_W)
				 + ',height=' + (h || POPUP_H)
				 + ',scrollbars=' + (s ? 'yes,' : 'no,')
				 + (args[i] || POPUP_EXTRAS);
	var win = window.open(url, target, features);
	win.focus();
	return false;
}
// END POP UP

function imageLoader(a) {
 if (document.images) {
  if (!document.p) document.p=new Array();
  var i, j=document.p.length;
  for (i=0; i<a.length; i++)
   if (a[i].indexOf("#")!=0) { document.p[j] = new Image; document.p[j++].src = a[i]; }
 }
}
function preloadImages() {
 imageLoader(preloadArray);
}

// list images to preload here:
var preloadArray = [
"../_images/nav/reserve_mo.gif",
"../_images/nav/calendar_mo.gif",
"../_images/nav/ticketsearch_mo.gif",
"../_images/nav/eventlistings_mo.gif",
"../_images/nav/discountpackages_mo.gif",
"../_images/nav/orderinginfo_mo.gif",
"../_images/nav/home_mo.gif"
];

// start preloading images after page load
if (window.addEventListener) {
 window.addEventListener("load", preloadImages, true);
} else if (window.attachEvent) {
 window.attachEvent("onload", preloadImages);
} else {
 window.onload = preloadImages;
}

HOVER_X = "_mo"; // mouse-over extension
// USAGE: swap(this, ['newimage.gif'])
function swap(i) {
 if (document.images && i.childNodes) {
  var a = swap.arguments[1], s = i.childNodes[0];
  if (a) s.src = a;
  else {
   var x = s.src.lastIndexOf('.'), xl = HOVER_X.length;
   if (s.src.substring(x-xl, x) == HOVER_X)
    s.src = s.src.substring(0,x-xl)+s.src.substring(x,s.src.length);
   else s.src = s.src.substring(0,x)+HOVER_X+s.src.substring(x,s.src.length);
  }
 }
}




Event.observe(window, "load", function() {
    hideDiv("input.facility_button");
  // setCurrentNavItem($$("ul.browse_genre li a"));
    viewMyCart();
    viewPromoHelp();
});







function hideDiv(name) {
    if($$(name).length == 0) {
        return;
    }
    $$(name)[0].hide();
}


function setCurrentNavItem(links) {                   // Passing the array in.                          
    for (var i=0; i<links.length; i++) {              // Declare 'i' before using it.
        if (links[i].href == location.href) {         // Use '.href' instead of getAttribute
                                                      // resolves Fully Qualified Name.
            $(links[i].parentNode).addClassName('on');// Use '$' to extend the parent node
        }                                             //   before using 'addClassName' method.

    }   

}





function addRow(obj) {      
   var tr = obj.parentNode.parentNode;                                      // grab parent TR
   var selects = tr.getElementsByTagName("SELECT");                        // grab all SELECTS   
   var seatCount = selects[0].options[selects[0].selectedIndex].value;    // grab first select (number of seats) and grab value
   var totalInput = tr.getElementsByTagName("INPUT")[0];                 // grab input field in row (where we will be displaying price)
   
   if (selects[1]) {                                                    // if there is another drop down for selecting price grab its selected value
        var ticketPrice =  selects[1].options[selects[1].selectedIndex].value;     
        rowValue(seatCount * ticketPrice, totalInput);                  // multiply the number of seats and ticket price, send to convert and put in input   
        toggleRow(selects[0]);  // toggle row color
                                  
    } else {     
        calcFixedPrice(tr, seatCount, totalInput);
        toggleRow(selects[0]);  // toggle row color

    }
            
                      
}

    function toggleRow(obj) {       // Set highlight class on selected Rows
        if ((obj.options[obj.selectedIndex].value) != 0) {
            var getRow = $(obj.parentNode.parentNode);                          // Use '$' to extend the parent node
            getRow.removeClassName("alternate").addClassName("highlight");      // remove previous background class, and replace with highlight class
        } else {
            var getRow = $(obj.parentNode.parentNode);                          // Use '$' to extend the parent node
            getRow.removeClassName("alternate").removeClassName("highlight");   // remove highligh class if select is equal to zero
        }
    }	
		


   function rowValue(rowTotal, totalInput) {   
        rowTotal = parseFloat(rowTotal);            // convert to Float
        rowTotal = rowTotal.toFixed(2);             // add fixed decimal     	    totalInput.value = "$" + rowTotal;          // display dollar sign and final value in input field of row	    	    totalType = "singleSeries";       // this function only called for singleSeries so we can pass this as an indicator	    grandTotalCalc(totalType);       // recalculate final values
    }
    
    

    function calcFixedPrice(tr, seatCount, totalInput) {
        var hiddenSelect = $(tr).down('td.select_fixed');         // get the fixed value in the curret row    
        var ticketPrice = hiddenSelect.firstChild.nodeValue;             // get the hidden input value
        var stripDollar = ticketPrice.replace(new RegExp("\\$\\b"), "");    // strip out dollar sign
        var ticketPrice = parseFloat(stripDollar);  
        var rowTotal = ticketPrice.toFixed(2);  
        totalInput.value = "$" + ((seatCount * ticketPrice).toFixed(2)) ;          // display dollar sign and final value in input field of row
        
        var subsCheck = $$('table.orderform_path tr th.family_pack');   // checking if family pack prices are in this table
        if (subsCheck.length != 0) {
            totalType = "familySeries";       // since there are family pack prices, we know this total should be put as family pack value	        grandTotalCalc(totalType);       // recalculate final values
        }
        else {
           totalType = "subsSeries";       // since it's not a family pack, it's a normal subs package	       grandTotalCalc(totalType);       // recalculate final values
        }
        
        
    }


 

     function grandTotalCalc(totalType) {
        if($$('td.totals').length == 0) {
            return;
        }   
        
        if ($('totalPreview')) {                        // for shared totals control remove totals class name so that total isn't duplicated
           var totalPreview = $('totalPreview');
           var childTd = totalPreview.getElementsByTagName("TD");
           for (var i=0; i<childTd.length; i++) {
                if (childTd[i].className == "totals") { 
                    var newClass = childTd[i].removeClassName("totals");
                }
            }
        }
        
        
        var totalTd = $$('td.totals');                       // grab all tds with final total results
        var grandTotalTd = $$('td.grandTotal');              // grab grand total TD
  
        
        if (totalType == "singleSeries") {
        		totalTd[0].innerHTML = eventTotal();           // in first total cell, display single event totals
        }        
        
        if (totalType == "subsSeries") {
        		totalTd[1].innerHTML = eventTotal();           // in second total cell, display subs event totals
        } 
        
         if (totalType == "familySeries") {
        		totalTd[2].innerHTML = eventTotal();           // in third total cell, display family packs totals
        } 
        

        
        grandTotalTd[0].innerHTML = grandTableCalc(totalTd);    // in first grand total cell, display total td results
        grandTotalTd[1].innerHTML = grandTableCalc(totalTd);    // in minidiv which is the second grand total cell, display total td results

    }






function eventTotal() {
    var totalInputs = $$('input.RowValue');             // grab all total inputs from end of rows
    var total = 0;                                      // initialize counter
    for (var i=0; i<totalInputs.length; i++) {  
        if (totalInputs[i].value != "") {               // for each input with a string value (aka client has selected price)
            var allValues = totalInputs[i].value.replace(new RegExp("\\$\\b"), "");     // strip out tollar sign
            total = parseFloat(allValues) + total;      // add to overall total 
        }
    }
        total = parseFloat(total);                      // convert total to float
        total = "$" + total.toFixed(2);                 // add dollar sign
        return total;                                   // return total to be displayed
    
}




function grandTableCalc(allTotals) {
    var total = 0;                                      // initialize counter
    for (var i=0; i<allTotals.length; i++) {  
        var tdTotals = allTotals[i].firstChild.nodeValue;           // grab total from all tds
        var allValues = tdTotals.replace(new RegExp("\\$\\b"), ""); // grip out dollar sign
        total = parseFloat(allValues) + total;                      // add total each time       
    }
        total = parseFloat(total);                      // convert total to float
        total = "$" + total.toFixed(2);                 // add dollar sign
        return total;                                   // return grand total to be displayed

}


function viewMyCart() {
    if(! $('totalPreview')) {
        return;
    }   
    $('viewCart').observe('click', respondToClick);
    function respondToClick(event) {
      var element = $(Event.element(event));
      $('totalPreview').toggle();               // toggle total preview div to hide / show when view cart div is clicked
      
    }
}

function viewPromoHelp() {
    if(! $('aboutPromoCode')) {
        return;
    }   
    $('promoCodeHelpButton').observe('click', respondToClick);
        
    function respondToClick(event) {
      var element = $(Event.element(event));
      $('aboutPromoCode').toggle();               // toggle total preview div to hide / show when view cart div is clicked
      
    }
}