/* !!NOTOKENS!!
   $Id: movies-ajax.js,v 1.22 2009/04/04 00:31:14 mleite Exp $
   $Source: /home/np/shared/filmcom/static/js/movies-ajax.js,v $
*/

var http_request = false;
var results = "";
var dateVariantSub = 0;
var iShowings = 0;

function makeRequest(url, zip, dateVariant)
{
  dateVariantSub = dateVariant;
  http_request = false;
  if( window.XMLHttpRequest )
  {
    http_request = new XMLHttpRequest();
    if (http_request.overrideMimeType) {
          http_request.overrideMimeType('text/xml');
       }
  }
  else if( window.ActiveXObject )
  {
    var msxmls = new Array( "Msxml2.XMLHTTP.5.0",
    "Msxml2.XMLHTTP.4.0",
    "Msxml2.XMLHTTP.3.0",
    "Msxml2.XMLHTTP",
    "Microsoft.XMLHTTP" );

    for( var i = 0; i < msxmls.length; i++ )
    {
      try
      {
        http_request = new ActiveXObject( msxmls[ i ] );
      }
      catch( e )
      {}
    }
  }

  if (!http_request) {
    alert('Cannot create XMLHTTP instance');
    return false;
  }

   perfDate = new Date();
   changeDate(perfDate, dateVariant);

  getDateVariants(zip, dateVariant);

  var showDate = "" + perfDate.getFullYear() + (perfDate.getMonth() + 1 < 10 ? "0" + (perfDate.getMonth() + 1) : perfDate.getMonth() + 1) + (perfDate.getDate() < 10 ? "0" + perfDate.getDate() : perfDate.getDate());

  var dist = document.getElementById("dist");
  var distance = dist.options[dist.selectedIndex].value != null ? dist.options[dist.selectedIndex].value : 5;
  parameters = "?zip=" + zip + "&dist=" + distance + "&showdate=" + showDate;

  http_request.onreadystatechange = movieContents;
  http_request.open('GET', url + parameters, true);
  http_request.send(null);
}

function getDateVariants(zip, dateVariant)
{
  var re = new RegExp(/^\d{5}$/);
  if (zip != '' && zip.match(re))
  {

      var today = new Date();
      var newDate = new Date();
      var strToday = "Today " + (today.getMonth() + 1) + "/" + today.getDate() + "/" + today.getFullYear() + "&nbsp;|&nbsp;";

      if (dateVariant > 0)
      {
        changeDate(newDate, dateVariant);
        strToday = "<a href=\"JavaScript:do_xml('" + zip + "',0)\">Today " + (today.getMonth() + 1) + "/" + today.getDate() + "/" + today.getFullYear() + "</a>&nbsp;|&nbsp;"
      }

      var strDay = "";
      var dayStr = "<span class=\"showDayText\"><b>" + strToday + "</b>";

      for (var d=1;d<7;d++)
      {
        var day = (today.getDay() + d) > 6 ? (today.getDay() + d)-7:(today.getDay() + d);

        switch (day)
        {
          case 0 : strDay = "Sun";break;
          case 1 : strDay = "Mon";break;
          case 2 : strDay = "Tue";break;
          case 3 : strDay = "Wed";break;
          case 4 : strDay = "Thu";break;
          case 5 : strDay = "Fri";break;
          case 6 : strDay = "Sat";break;
        }

        if (day == newDate.getDay())
          dayStr += "<b>" + strDay + "</b>&nbsp;|&nbsp;";
        else
          dayStr += "<a id=\"d_" + d + "\" href=\"JavaScript:do_xml('" + zip + "'," + d + ")\">" + strDay + "</a>&nbsp;|&nbsp;";
      }
      document.getElementById("showdays").innerHTML = dayStr.substring(0,dayStr.lastIndexOf("|") - 1) + "</span>";
  }
}

function movieContents()
{
  var allres = "";
  var xmldoc;
  iShowings = 0;

  if (http_request.readyState == 4) {
    document.getElementById("spinner").innerHTML = "";
	var radius = document.getElementById("dist").value;
    if (http_request.status == 200) {
      if ( window.ActiveXObject ) {
        xmldoc = new ActiveXObject("Msxml2.DOMDocument.3.0");
        xmldoc.async = false;
        xmldoc.loadXML(http_request.responseText);
        var theaters = xmldoc.selectSingleNode("//radius/theaters");
      }
      else
      {
          var csDOMParser = new DOMParser();
          xmldoc = csDOMParser.parseFromString(http_request.responseText,"text/xml");
        var theaters = xmldoc.getElementsByTagName("theaters")[0];
      }

      var houses = theaters.getElementsByTagName("house");

      for (var i=0; i<houses.length;i++)
      {
        var house = houses[i];
        if (house.getElementsByTagName("schedule")[0].hasChildNodes())
        {
          var name = house.getElementsByTagName("name")[0].firstChild.nodeValue;
          var house_id = house.getElementsByTagName("house_id")[0].firstChild.nodeValue;
          var ticketing = house.getElementsByTagName("ticketing")[0].firstChild.nodeValue == "True";
          var address = house.getElementsByTagName("address")[0];
          var street = address.getElementsByTagName("street")[0].firstChild.nodeValue;
          var city = address.getElementsByTagName("city")[0].firstChild.nodeValue;
          var state = address.getElementsByTagName("state")[0].firstChild.nodeValue;
          var zip = address.getElementsByTagName("zip")[0].firstChild.nodeValue;
          var phone = address.getElementsByTagName("phone")[0].firstChild.nodeValue;
          var schedule = house.getElementsByTagName("schedule")[0];

          allres += genHouse(name, address, results, i);
          allres += "<div class=\"showtime_width\" id=\"house" + i + "-content\">";
          allres += "<table class=\"showtime_width\"><tr><td>";
          allres += street + "<br>";
          allres += city + ", " + state + "&nbsp;" + zip + "<br>";
          allres += phone;
          allres += "</td>";

          if (ticketing)
            allres += "<td><a href=\"http://www.movietickets.com/\"><img src=\"" + imgLocStr + "/images/global/movietixcom.gif\" border=\"0\"></a></td>";

          allres += "<td align=\"right\">";

          var allAtts = "";

          var attributes = house.getElementsByTagName("attributes")[0];
          if (attributes.firstChild)
          {
            var atts = attributes.firstChild.nodeValue;
            if (atts && atts.indexOf("handicap") >= 0)
            allAtts += "&nbsp;<img src=\"" + imgLocStr + "/images/global/icon01.gif\"/>";

            if (atts && atts.indexOf("hearing") >= 0)
            allAtts += "&nbsp;<img src=\"" + imgLocStr + "/images/global/icon04.gif\"/>";
          }

          var sounds = house.getElementsByTagName("sounds")[0];
          if(sounds.getElementsByTagName("sound")[0])
          allAtts += "&nbsp;<img src=\"" + imgLocStr + "/images/global/icon02.gif\"/>";

          var seating = house.getElementsByTagName("seating")[0];
          if (seating.firstChild && seating.firstChild.nodeValue == "Stadium")
          allAtts += "&nbsp;<img src=\"" + imgLocStr + "/images/global/icon03.gif\"/>";

          allres += allAtts + "</td></tr></table>"
          allres += getShowings(schedule, ticketing, house_id, dateVariantSub);
          allres += "</div>";

        }
      }
      if (iShowings > 0)
      {
        document.getElementById("basic-accordian").innerHTML = allres;
        new Accordian('basic-accordian',5,'header_highlight');
      }
      else
      {
        errHtml = "<br>There are currently no theaters available within " + radius + " miles of zip code<br><br>";
        errHtml += "<b>Please Try:</b><br><br>";
        errHtml += "<ul><li> Extending your search radius, or<li>Entering a new zip code, or<li>Choosing another date.</ul>";
        document.getElementById("basic-accordian").innerHTML = errHtml;
      }
    }
    else
    {
      alert('There was a problem with the request.');
    }
  }
}

function do_xml(zip, dateVariant) {
  var re = new RegExp(/^\d{5}$/);
  if (zip != '' && zip.match(re))
  {
    document.getElementById("spinner").innerHTML = "<img src=\"" + imgLocStr + "/images/icons/ajax-loader.gif\"/>";
    makeRequest('/movielistingsXML', zip, dateVariant == null ? 0 : dateVariant);
  }
  else
    document.getElementById("basic-accordian").innerHTML = "We need you to enter a zip code to show you show times in your area. Please enter a zip code and try again.";

}

function genHouse(name, address, results, housenum)
{
  var street = address.getElementsByTagName("street")[0].firstChild.nodeValue;
  var city = address.getElementsByTagName("city")[0].firstChild.nodeValue;


  results += "<div class=\"showtimes_header\" id=\"house" + housenum + "-header\">";
  results += "<div style=\"cursor:pointer;text-align:left;height:21px;background-repeat:repeat-x;background-position:top;color:#4B80A2;font-family:Arial, sans-serif;font-size:13px;font-weight:700;float:left;line-height:21px;text-transform:capitalize;\" onmouseover=\"this.style.color='#E58D2E'\" onmouseout=\"this.style.color='#4B80A2'\">";
  results += "<span id=\"house" + housenum + "expand\">+&nbsp;</span>" + name + "</div>";
  results += "<div style=\"text-align:right;height:21px;background-position:top;color:#000000;font-family:Arial, sans-serif;font-size:12px;float:right;line-height:21px;text-transform:capitalize;\">" + street + " - " + city + "</div>";
  results += "</div>";


  if (results != "undefined")  return results;
  else return "";
}

function changeDate(dateVar, variant)
{
  return  dateVar.setDate(dateVar.getDate() + variant);
}

function getShowings(schedule, ticketing, house_id, dateVariant)
{

  var movies = schedule.getElementsByTagName("movie");
  var showings = "<div class=\"accordion_child\">";


  var today = new Date();
  changeDate(today, dateVariant);

    var perfd = "" + (today.getMonth() + 1 < 10 ? "0" + (today.getMonth() + 1) : today.getMonth() + 1) + today.getDate() + today.getFullYear();


  for (var m=0;m<movies.length;m++)
  {

    var movie = movies[m];
    var movie_name = movie.getElementsByTagName("movie_name")[0].firstChild.nodeValue;
    var movie_id = movie.getElementsByTagName("movie_id")[0].firstChild.nodeValue;
    var rating;
    if (movie.getElementsByTagName("movie_rating")[0].firstChild)
       rating = movie.getElementsByTagName("movie_rating")[0].firstChild.nodeValue;

    movieLinkName = movie_name.replace(" ","-");


    showings += "<a class=\"movie_item\" href=\"/movies/"+ movieLinkName + "?cs-id=" + movie_id + "\">" + movie_name + "</a> (" + rating + "):&nbsp;";

    var showArr = new Array();
    var showtimes = movie.getElementsByTagName("showtime");
    for (var t=0;t<showtimes.length;t++)
      showArr[t] = showtimes[t].firstChild.nodeValue;

    showArr.sort();

    var href = "";
    iShowings += showArr.length;

    for (var t=0;t<showArr.length;t++)
    {
        tempShowtime = showArr[t].split(":");
        sTime = tempShowtime[0] > 12 ? (tempShowtime[0] - 12) + ":" + tempShowtime[1] : showArr[t];
      if (ticketing)
      {
        href = "https://www.movietickets.com/purchase.asp?afid=film&amp;movie_id=" + movie_id + "&amp;house_id=" + house_id + "&amp;perfd=" + perfd + "&amp;perft=" + showArr[t];
        showings += "<a href=\"" + href + "\" target=\"_new\">" + sTime + "</a>&nbsp; | &nbsp;";
      }
      else
        showings += sTime + "&nbsp; | &nbsp;";
    }
    showings = showings.substring(0,showings.lastIndexOf("|") - 1);
    showings += "<br>";
  }
  showings += "</div>";
  return showings;
}



/*
DezinerFolio.com Simple Accordians.

Author  : G.S.Navin Raj Kumar
Website : http://dezinerfolio.com

*/

/*
* The Variable names have been compressed to achive a higher level of compression.
*/

// Prototype Method to get the element based on ID
function $(d){
  return document.getElementById(d);
}

// set or get the current display style of the div
function dsp(d,v){
  if(v==undefined){
    return d.style.display;
  }else{
    d.style.display=v;
  }
}

// set or get the height of a div.
function sh(d,v){
  // if you are getting the height then display must be block to return the absolute height
  if(v==undefined){
    if(dsp(d)!='none'&& dsp(d)!=''){
      return d.offsetHeight;
    }
    viz = d.style.visibility;
    d.style.visibility = 'hidden';
    o = dsp(d);
    dsp(d,'block');
    r = parseInt(d.offsetHeight);
    dsp(d,o);
    d.style.visibility = viz;
    return r;
  }else{
    d.style.height=v;
  }
}
/*
* Variable 'S' defines the speed of the accordian
* Variable 'T' defines the refresh rate of the accordian
*/
s=7;
t=10;

//Collapse Timer is triggered as a setInterval to reduce the height of the div exponentially.
function ct(d){
  d = $(d);
  if(sh(d)>0){
    v = Math.round(sh(d)/d.s);
    v = (v<1) ? 1 :v ;
    v = (sh(d)-v);
    sh(d,v+'px');
    d.style.opacity = (v/d.maxh);
    d.style.filter= 'alpha(opacity='+(v*100/d.maxh)+');';
  }else{
    sh(d,0);
    dsp(d,'none');
    clearInterval(d.t);
  }
}

//Expand Timer is triggered as a setInterval to increase the height of the div exponentially.
function et(d){
  d = $(d);
  if(sh(d)<d.maxh){
    v = Math.round((d.maxh-sh(d))/d.s);
    v = (v<1) ? 1 :v ;
    v = (sh(d)+v);
    sh(d,v+'px');
    d.style.opacity = (v/d.maxh);
    d.style.filter= 'alpha(opacity='+(v*100/d.maxh)+');';
  }else{
    sh(d,d.maxh);
    clearInterval(d.t);
  }
}

// Collapse Initializer
function cl(d){
  if(dsp(d)=='block'){
    clearInterval(d.t);
    d.t=setInterval('ct("'+d.id+'")',t);
  }
}

//Expand Initializer
function ex(d){
  if(dsp(d)=='none'){
    dsp(d,'block');
    d.style.height='0px';
    clearInterval(d.t);
    d.t=setInterval('et("'+d.id+'")',t);
  }
}

// Removes Classname from the given div.
function cc(n,v){
  s=n.className.split(/\s+/);
  for(p=0;p<s.length;p++){
    if(s[p]==v+n.tc){
      s.splice(p,1);
      n.className=s.join(' ');
      break;
    }
  }
}
//Accordian Initializer
function Accordian(d,s,tc){
  // get all the elements that have id as content
  l=$(d).getElementsByTagName('div');
  c=[];
  for(i=0;i<l.length;i++){
    h=l[i].id;
    if(h.substr(h.indexOf('-')+1,h.length)=='content'){c.push(h);}
  }
  sel=null;
  //then search through headers
  for(i=0;i<l.length;i++){
    h=l[i].id;

    if(h.substr(h.indexOf('-')+1,h.length)=='header'){
      d=$(h.substr(0,h.indexOf('-'))+'-content');
      d.style.display='none';
      d.style.overflow='hidden';
      d.maxh =sh(d);
      d.s=(s==undefined)? 7 : s;
      h=$(h);
      h.tc=tc;
      h.c=c;

      // set the onclick function for each header.
      h.onclick = function(){
        if (this.className.indexOf(tc) > 0)
        {
          this.style.borderBottom = "thin dotted #CECECE";
          id = this.id.substr(0,this.id.indexOf('-'));
          expandDiv = $(id + "expand");
          expandDiv.innerHTML = "+&nbsp;"
          obj = $(id+'-content')
          obj.style.borderBottom = "0";
          cl($(id+'-content'));
          cc($(this.id),'');
        }
        else
        {
          for(i=0;i<this.c.length;i++){
            this.style.borderBottom = "0";
            cn=this.c[i];
            n=cn.substr(0,cn.indexOf('-'));
              if((n+'-header')==this.id){
              ex($(n+'-content'));
              expandDiv = $(n + "expand");
              expandDiv.innerHTML = "-&nbsp;"
              obj=$(n+'-content');
              if(obj)
                obj.style.borderBottom = "thin dotted #CECECE";
              n=$(n+'-header');
              cc(n,'__');
              n.className=n.className+' '+n.tc;

            }
          }
        }
      }
      if(h.className.match(/selected+/)!=undefined){ sel=h;}
    }
  }
  if(sel!=undefined){sel.onclick();}
}