var DD_belatedPNG = null;

//?? MOVE THIS ELSEWHERE
$(document).ready(function() {

  // Make URL input fields valid when losing focus
  makeValidURLsOnFocusOut();

  // Validate news letter signup forms
  validateNewsletterSignup();
  
  // Validate review forms
  validateReviewForm();
  
  // Validate contact us forms
  validateContactForm();
  
  // Build Company Links
  buildCompanyVenuLinks();
  
//?? Move this elsewhere
  //Extends 'show description panel' to the 'bookmark' bar if the image on the ride hand side
  //extends further down the page than the description
  var descContainer = $("#show_container #show_left_container #show_content #show_desc");
  var imgContainer = $("#show_container #show_right_container #show_img");
  if( descContainer.length > 0 && imgContainer.length > 0  ){
    var descExtentY = $(descContainer).offset().top + $(descContainer).outerHeight();
    var imgExtentY = $(imgContainer).offset().top + $(imgContainer).outerHeight();
    if( descExtentY < imgExtentY ){
      var heightDifference = imgExtentY - descExtentY;
      var newDescContainerHeight = $(descContainer).height() + heightDifference;
      $(descContainer).css("height",newDescContainerHeight + "px");
    }
  }
  
  //makeHoverIE6(".shogo_search");
  fixSearchIE6();
  
  //Fix all PNG assets
  fixPngAssets();
  
  fixGoRolloversIE6();
});

function fixPngAssets(){
  if(DD_belatedPNG !== null){
    DD_belatedPNG.fix(".pngfix");
  }
}

function fixGoRolloversIE6(){
  if($.browser.msie && parseInt($.browser.version) < 7){
    var goButtons = $(".book");
    makeHoverIE6(goButtons);
  }
}

function fixSearchIE6(){
  if($.browser.msie && parseInt($.browser.version) < 7){
    var goButtons = $(".shogo_search");
    $(goButtons).each(function(){
    
      var selectField = $(this).parent().find("select");
      if( selectField != null ){
        var selectWidth = $(selectField).width();
      }
      var buttonWidth = $(this).width();
    
      $(this).mouseenter(function(){
        $(this).addClass("hover");
        if( selectField != null ){
          var newButtonWidth = $(this).width();
          var newSelectWidth = selectWidth - (newButtonWidth - buttonWidth);
          $(selectField).css("width", newSelectWidth + "px");
        }
      });
      $(this).mouseleave(function(){
        $(this).removeClass("hover");
        if( selectField != null ){
          $(selectField).css("width", selectWidth + "px");
        }
      });
    
    });
  };
}

function makeHoverIE6(elem){
  if($.browser.msie && parseInt($.browser.version) < 7){
    $(elem).each(function(){
      $(this).mouseenter(function(){
        $(this).addClass("hover");
      });
      $(this).mouseleave(function(){
        $(this).removeClass("hover");
      })
    });
  }
}

function buildCompanyVenuLinks(){
  
  // If company venu block exists, build links
  if($("#compvens").length > 0){
    // Get all venus
    var venus = $(".compven_block")
    
    //Build links for each venu
    $(venus).each(function(){
      var link = $(this).find(".compven_name a");
      if($(link).length > 0){
        $(this).click(function(){
          window.location.pathname = $(link).attr("href");
          // window.location.assign(window.location.protocol + "//" + window.location.hostname + ":" +
          //   window.location.port + $(link).attr("href"));
        });
      }
    })
  }
  
}

// it saves days that have shows. it is used in disabling links on datepicker
var days_have_shows = [];
var flag_show_calender  = true;
var first_time = true;

//This method add event on page 
function addLoadEvent(func) {
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  }
  else {
    window.onload = function() {
      if (oldonload) {
        oldonload();
      }
      func();
    }
  }
}

// this method sends ajax request to server to get this months events
$(function(){
  if( $('#datepicker').val() != null){
    today = new Date();
    // i added 1 in month becuase javascript starts months from 0 - 11
    load_data_by_ajax_and_show_calender(today.getMonth() + 1 , today.getFullYear());
  }  
  
});

// setups the calender
function show_calender()
{
  // Datepicker
    $('#datepicker').datepicker({
      dateFormat: 'yy-mm-dd', 
      inline: true ,  
      onSelect: function(dateText, inst) { performances(dateText);} ,    
      beforeShowDay: function(date) {return disable_dates_on_calender(date) },
      onChangeMonthYear: function(year, month, inst) { 
               if(first_time == false){
                 load_data_by_ajax_and_show_calender(month , year);                  
              }   
              first_time = false;
        }
    });            
    $('#datepicker').datepicker('option', 'prevText', 'Previous Month');
    $('#datepicker').datepicker('option', 'nextText', 'Next Month');
    $('#datepicker').datepicker('option', 'dayNamesMin', ['S','M','T','W','T','F','S']);
    

}

//send ajax requst to days of the month that have performances
//then it setups calender by calling show_calender first time
//if it is called through onMonthChange then it will send ajax request and update calender accordingly
function load_data_by_ajax_and_show_calender(month , year){  
  //ajax
  $.ajax({
    type: "GET",
    url: "/performances_by_month/"+month + "/" + year,
    data: "",
    success: function(html){
        var array = html.split(",");
        days_have_shows = array;       
        if(flag_show_calender == true )
          show_calender(); 
        else
        {
           DP_jQuery.datepicker._public_update_datepicker('#datepicker');            
        }  
        flag_show_calender = false;  
        
      }
  });
  
}

//checks current day and month exist in show_days array that holds comma seprated days of the month that have performances
//it also return true if the date is equals to todays date
function have_show(show_days , day , month){
         for (var i = 0; i < show_days.length ; i++){         
            if(show_days[i] == day)              
              return true;
          }
          today = new Date();
          if(day == today.getDate() && today.getMonth() == month)
            return true;
            
          return false;
}

//this method is called on beforeShowDay event of calender
//it checks that date that is passed in parameter have performances or not by calliing have_show method
//
function disable_dates_on_calender(date)
{  
  var flag = have_show(days_have_shows , date.getDate());    
  var title = flag ? 'Click to see the performances' : 'There is no performance on '+date;
  return [flag , '' , title]; 
}


function highlight(object)
{
  //ajax
  $.ajax({
    type: "GET",
    url: "/admin/shows/highlight/"+object.id,
    data: "value="+object.checked,
    beforeSend: function(html){
      $("#progress_"+object.id).html("updating");
    },
    error: function(html){      
      $("#progress_"+object.id).html("Failed");
      },
    success: function(html){      
      $("#progress_"+object.id).html("Updated");
      }
  });
  
}

function performances(date){
  //ajax
  $.ajax({
    type: "GET",
    url: "/performances_by_date/"+date,
    data: "",
    success: function(html){
      $("#performances").html(html);                                    
      }
  });
};


function changeURL(formid , selectid){
  
  document.getElementById(formid).action = $("#"+selectid).val();
  return true;
}



//feedback form check
function checkLength(tips, o,n,min,max ) {

    if ( o.val().length > max || o.val().length < min ) {
            o.addClass('ui-state-error');
            //updateTips(tips , "Length of " + n + " must be between "+min+" and "+max+".");
            return false;
    } else {
            return true;
    }

}
                
function checkMail(o)
{
        var x = o.val();
        var filter = /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i;
        //var filter  = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
        if (filter.test(x)) return true;
        else 
        {
          o.addClass('ui-state-error');
          return false;
        }  
}
                
function updateTips(tips , t) {
        tips.text(t).effect("highlight",{},1500);
}
                
// function validate_feedback(){
//     var email = $("#feedback_email"), name = $("#feedback_name") , body = $("#feedback_body") , 
//         allFields = $([]).add(email).add(name).add(body),
//         tips = $("#validateTips");
//     
//         var bValid = true;
//         allFields.removeClass('ui-state-error');
//         
//         bValid = bValid && checkLength(tips , name,"name" , 2 , 50);                                       
// 
//         bValid = bValid && checkMail(email);                
//         
//         bValid = bValid && checkLength(tips , body, "feedback" , 2 , 50000);                                       
//         
//         return bValid;
//                     
// }

// function validate_review(){
//     var email = $("#review_reviewer_email"), name = $("#review_reviewer_name") , extract = $("#review_extract") , 
//         title = $("#review_title") , agree = $("#agree"),
//         allFields = $([]).add(email).add(name).add(extract).add(title).add(agree),
//         tips = $("#validateTips");
//     
//         var bValid = true;
//         allFields.removeClass('ui-state-error');
//         
//         bValid = bValid && checkLength(tips , name,"name" , 2 , 50);                                       
// 
//         bValid = bValid && checkMail(email);                
//         
//         bValid = bValid && checkLength(tips , title,"title" , 2 , 255);                                       
//         
//         bValid = bValid && checkLength(tips , extract, "extract" , 2 , 50000);                                
//                 
//         bValid = bValid && agree.is(':checked');
//         
//         if(agree.is(':checked') != true)
//           alert("Please accept terms & conditions");
//         return bValid;
//                     
// }

// This loads all the required javascript for the feature page
// It controls the function of the cycle plugin for the rotating images/text on the front page,
// the add_to_fav function and the toggle drop down functionality of the book now option.
function feature_page_load(){
  //$(function() {
    $('#pause').click(pauseResume);
    			
    $('#feature_fade').cycle({
      fx: 'fade',
      timeout: 8000,
      next: '#next', 
      prev: '#prev'
    });
  //});
  $('.bookmark').jFav();
  $("a.show_booking_show").click(featureBooking);
}

// This allows the pause button to become a resume button and vice versa
function pauseResume() {
  var button = $('#pause')
  var slide = $('div#feature_booking')
  if( button.hasClass('resume'))
    {
      if( slide.is(':open') ){
          //Close all opened booking lists
          if($.browser.msie && parseInt($.browser.version) < 8){
            $(slide).hide(0);
          }else{
            $(slide).slideUp('normal');
          }
          resumeOpen();
      }
    }
  else
    {
      $(button).addClass("resume");
      $('#feature_fade').cycle('pause');
    }
}

function resumeOpen() {
  var button = $('#pause')
  $(button).removeClass("resume");
  $("#feature_fade").cycle('resume',true);
}

// This toggles the drop down functionality of the book now
// It also pauses the cycle plugin and then resumes (not working 100% as expected)
function featureBooking(){

  var features = $("#feature_fade").children();
  var currentFeature = null;
  
  //Find feature that is completely opaque (this is our current feature)
  $(features).each(function(){
    var opacity = $(this).css("opacity");
    if(opacity == 1 || opacity == "1" || opacity == "1.0"){
      currentFeature = $(this);
    }
  });
  
  //If we found a feature is not fading in or out
  if(currentFeature !== null){
    
    var bookings = $(currentFeature).find("div#feature_booking");
    var bookingsCollapsed = $(bookings).css("display") == "none";
    
    if( $(bookings).children().length > 0 ){
      
      if(bookingsCollapsed){
        slideDownBookings( $(currentFeature).find("div#feature_booking") );
      }else{
        slideUpBookings( $(currentFeature).find("div#feature_booking") );
      }

      //$("div#feature_booking").slideToggle('normal', toggleResumePause());
    }
  }
  return false;
}

function slideDownBookings( booking_elem ){
  
  if($.browser.msie && parseInt($.browser.version) < 8){
    pause();
    $(booking_elem).stop().show(0);
  }else{
    pause();
    $(booking_elem).stop().slideDown('normal');
  }
  
}

function slideUpBookings( booking_elem ){
  
  if($.browser.msie && parseInt($.browser.version) < 8){
    $(booking_elem).stop().hide(0);
    resumeOpen();
  }else{
    $(booking_elem).stop().slideUp('normal',function(){
      $(this).hide(0);
      resumeOpen();
    });
  }
  
}

function toggleResumePause() {
  var button = $('#pause');
  if( button.hasClass('resume'))
    {
      $(button).removeClass("resume");
      $("#feature_fade").cycle('resume',true);
    }
  else
    {
      $(button).addClass("resume");
      $('#feature_fade').cycle('pause');
    }
}

function pause(){
  var button = $('#pause');
  $(button).addClass("resume");
  $('#feature_fade').cycle('pause');
}

// This loads all the required javascript for the show page
// Same as the feature page function except no cycle plugin
function show_page_load(){
  $('.bookmark').jFav();
  $("a.show_booking_show").click(showBooking);
}

// This toggles the drop down functionality of the book now
function showBooking(){
  if($.browser.msie && parseInt($.browser.version) < 8){
    $("div#show_booking").toggle(0);
  }else{
    $("div#show_booking").slideToggle();
  }
  return false;
}

// Ensures URLs begin with "http://"
function makeValidURL(url){
  url = url.replace(/http:\/\//gi,"")
  url = "http://" + url;
  return url;
}

// Makes URLs valid when losing focus
function makeValidURLsOnFocusOut(){
  $("input.validURL").blur(function(){
    if( $(this).val().replace(/^\s*/, "").replace(/\s*$/, "") != "" ){
        $(this).val(makeValidURL($(this).val()));
    }
  })
}

function validateNewsletterSignup(){
  if( $("#newsletter_signup").length != 0 ){
    
    // Validate news letter signup forms
    var news_form = $("#newsletter_signup form");
    
// ?? IE HACK: fix this alter
    $(news_form).find("button").click(function(){
      $(news_form).submit();
    });
    
    $(news_form).validate({

      focusInvalid: false,

      //Handles the event in which the form is submitted
      submitHandler: function(form) {

        //Submit form
        form.submit();
      },

      //Required fields
      rules: { 
          "cm-name": { 
              required: true
          }, 
          "cm-ttbv-ttbv": {
              required: true,
              email: true
          },
          "cm-fo-zurdh": {
              required: true
          },
          "cm-fo-zutc": {
              required: true
          }
      },

      //Error messages
      messages: { 
        "cm-name": { 
            required: "Please enter your name"
        }, 
        "cm-ttbv-ttbv": {
            required: "Please enter your email address",
            email: "The email address you have provided is invalid"
        },
        "cm-fo-zurdh": {
            required: "Please select your gender"
        },
        "cm-fo-zutc": {
            required: "You must acknowledge the privacy collection notice"
        }
      },

      //Handles the event in which a form fails to validate
      invalidHandler: function(form, validator) {
        //Clear error messages
        $("#validation-notice").text("");
      },

      //Handles the placement of error messages on the page
      errorPlacement: function(error, element) {
        //If we have a div to report errors to and no errors have been reported yet...
        if($("#validation-notice").length != 0 && $("#validation-notice").text() == ""){
          //Add error message to notice DIV
          var validationNotice = $("#validation-notice")
          error.appendTo($(validationNotice))
          //Anchor to validation message
          window.location.hash = "validation";
        }
      }
    });
  }
}

function validateReviewForm(){
  if( $("#write_review").length != 0 ){
    
    // Validate news letter signup forms
    var review_form = $("#write_review form");
    
// ?? IE HACK: fix this later
    $(review_form).find("button").click(function(){
      $(review_form).submit();
    });
    
    $(review_form).validate({

      focusInvalid: false,

      //Handles the event in which the form is submitted
      submitHandler: function(form) {

        //Submit form
        form.submit();
      },

      //Error messages
      messages: { 
          "rev-name": { 
              required: "Please enter your name"
          }, 
          "rev-loc": {
              required: "Please enter your location"
          },
          "rev-email": {
              required: "Please enter your email address",
              email: "The email address you have provided is invalid"
          },
          "rev-title": {
              required: "Please enter a review title"
          },
          "rev-content": {
              required: "Please write your review"
          },
          "rev-terms": {
              required: "You must agree to the terms and conditions"
          }
      },

      //Required Fields
      rules: { 
        "rev-name": { 
            required: true
        }, 
        "rev-loc": {
            required: true
        },
        "rev-email": {
            required: true,
            email: true
        },
        "rev-title": {
            required: true
        },
        "rev-content": {
            required: true
        },
        "rev-terms": {
            required: true
        }
      },

      //Handles the event in which a form fails to validate
      invalidHandler: function(form, validator) {
        //Clear error messages
        $("#validation-notice").text("");
      },

      //Handles the placement of error messages on the page
      errorPlacement: function(error, element) {
        
        //If we have a div to report errors to and no errors have been reported yet...
        if($("#validation-notice").length != 0 && $("#validation-notice").text() == ""){
          //Add error message to notice DIV
          var validationNotice = $("#validation-notice")
          error.appendTo($(validationNotice))
          //Anchor to validation message
          window.location.hash = "validation";
        }
      }
    });
  }
}

function validateContactForm(){
  if( $("#abcon").length != 0 ){
    
    // Validate news letter signup forms
    var news_form = $("#abcon form")
    

// ?? IE HACK: fix this later
    $(news_form).find("button").click(function(){
      $(news_form).submit();
    });


    $(news_form).validate({

      focusInvalid: false,

      //Handles the event in which the form is submitted
      submitHandler: function(form) {

        //Submit form
        form.submit();
      },

      //Required fields
      rules: { 
          "feedback[name]": { 
              required: true
          }, 
          "feedback[email]": {
              required: true,
              email: true
          },
          "feedback[body]": {
              required: true
          }
      },

      //Error messages
      messages: { 
        "feedback[name]": { 
            required: "Please enter your name"
        }, 
        "feedback[email]": {
            required: "Please enter your email address",
            email: "The email address you have provided is invalid"
        },
        "feedback[body]": {
            required: "Please write your message"
        }
      },

      //Handles the event in which a form fails to validate
      invalidHandler: function(form, validator) {
        //Clear error messages
        $("#validation-notice").text("");
      },

      //Handles the placement of error messages on the page
      errorPlacement: function(error, element) {

        //If we have a div to report errors to and no errors have been reported yet...
        if($("#validation-notice").length != 0 && $("#validation-notice").text() == ""){
          //Add error message to notice DIV
          var validationNotice = $("#validation-notice")
          error.appendTo($(validationNotice))
          //Anchor to validation message
          window.location.hash = "validation";
        }
      }
    });
  }
}

function show_other_venue()
{
  if( $('#performance_venue_id').val() == "0"){
    if($.browser.msie && parseInt($.browser.version) < 8){
      $('#performance_other_venue').show(0);
    }else{
      $('#performance_other_venue').show('slow');
    }
  }else{
    if($.browser.msie && parseInt($.browser.version) < 8){
      $('#performance_other_venue').hide(0);
    }else{
      $('#performance_other_venue').hide('slow');
    }
  }

}


