// version 0.4 - disabled request a  callback lightbox, form now shows up on page. enabled clear form in Lightbox open.
var initPlansListing = function() {
  
    $('tr.hiddenblock').hide();
    $('a.toggler').click(function(){
        $(this).parents('tr').next('.hiddenblock').toggle();
        return false;
    });
    
    
  var plans_module = $(".plans-module"),
      toggles = $(plans_module).find("a.more-info");
      
  // There's no point in continuing unless these elements exist
  if (($(plans_module).length <= 0) || ($(toggles).length <= 0)) {
    return;
  }
  
  // Loop through each toggle
  $.each(toggles, function() {
  
    // Find its target table
    var table = $($(this).attr('href'));
    
    if (!table) {
      return false;
    }
    
    // First of all, hide the target element (table)
    $(table).hide();
    
    // This toggle elemet controls whether the table is shown or hidden (via clicking)
    $(this).toggle(
      function() {
        // Show table
        $(table).slideDown();
        // Change to Less info
        $(this).attr("title", "Hide the expanded information on Vodafone's Single Business Cap").text("hide plans").removeClass("more-info").addClass("less-info");
        
        // Prevent link action
        return false;
      },
      function() {
        
        // Hide table
        $(table).slideUp();
        // Change to more info
        $(this).attr("title", "More information on Vodafone's Single Business Cap").text("show plans").removeClass("less-info").addClass("more-info");
        
        // Prevent link action
        return false;
        
      }  
    );
    
  });
};
var initRequestCallBackLightbox = function() {
  
  var form = $("#request-a-call-back-form"),
      triggers;
      
  if ($(form).length <= 0) {
    return;
  }
  
  // Define add lightbox function
  var addLightBox = function() {  
    $(form).dialog({
      modal: true,
      draggable: false,
      resizable: false,
      title: '<img src="/business_reddot/images/global/vodafone_logo.gif" alt="Vodafone Logo" />',
      width: 560,
      position: ['center', 63],
      dialogClass: 'request-a-call-back-container',
      closeText: 'Close window',
      open: function(e) {
        checkLightboxContents();
      },
      close: function(e) {
        $(this).dialog('destroy');
      }
    });
  };
  // This function adds functionality to show/hide optional form fields
  var setupOptionals = function() {
    $(form).find("a.toggle-optional").bind("click", function(event) {
      $(this).parent("div.optional-container").toggleClass("show-optional").toggleClass("hide-optional");
      event.preventDefault();
    });
  };
  // This function toggles the form's text and fields visibility
  var toggleForm = function() {
    $(form).find("fieldset").toggle();
  };
  // This function is used upon opening to make sure that the opened dialog contains the form and not a thankyou from a previously submitted form
  var checkLightboxContents = function() {
    var thanks = $(form).find("p.thanks");
    if (thanks.length > 0) {
      // Remove any existing thankyou
      $(thanks).remove();
      // Clear the form
      $(form)[0].reset();
      // Toggle visibility of the form
      toggleForm();
      // Hide optional
      $(form).find(".optional-container").each(function() {
        // If this optional is hidden, leave it alone
        if ($(this).hasClass("hide-optional")) {
          return;
        } else {
          $(this).toggleClass("hide-optional").toggleClass("show-optional");
        }
      });
    }
  };
  // We want this form to use AJAX for submission
  var handleForm = function() {
    // When this form is submitted, it is to be validated and then sent via XHR
    $(form).validate({
      submitHandler: handleAjaxRequest,
      showErrors: handleFormValidationErrors,
      onclick: false,
      onkeyup: false,
      onfocusout: false,
      rules: {
        last_name: "required",
        '00N20000000hyDE': "number required",
        company: "required",
        '00N20000000hyCs': "number required",
       // industry: "required",
        state: "required",
       // existing_customer: "required",
        email: "email required"
      },
      messages: {
        last_name: "Please enter your contact name",
        '00N20000000hyDE': "Enter your contact number",
        company: "Please enter your company name",
        '00N20000000hyCs': "Enter your required number of connections",
        // industry: "Select your industry type",
        state: "Select your state",
        // existing_customer: "Are you an existing Vodafone customer?",
        email: "Please enter a valid email address"
      }
    });
  };
  var handleFormValidationErrors = function(errorMap, errorList) {
    var errorMessages = [],
        msgContainer = $("#error-messages");
    // Style invalid inputs
    $.each(errorList, function() {
      // Find the element's parent li
      var container = $(this.element).parents(".formList > li");
      // Add the error class if it needs it
      if (!$(container).hasClass("error")) {
        $(container).addClass("error");
      }
      // Add the message to the error messages array
      errorMessages.push('<li><label for="' + $(this.element).attr("id") + '">' + this.message + '</label></li>');
    });
    // Now, go through each li.error and make sure the field is supposed to be errored
    $(form).find(".formList > li.error").each(function() {
      // Find this li element's input(s)
      var fields = $(this).find("input, select, textarea"),
          fieldErrors = $.map(fields, function(el, i) {
            // Return whether this field has an error on it or not
            return (errorMap[$(el).attr("name")] !== undefined);
          });
      // If the fieldErrors array doesn't contain any true values
      if ($.inArray(true, fieldErrors) < 0) {
        // Remove the error class
        $(this).removeClass("error");
      }
    });
    // If the message container needs to be visible, show it
    if (errorMessages.length > 0) {
      // Show messages
      $(msgContainer).html("<p><strong>Please complete the following items:</strong></p><ul>" + errorMessages.join("\n") + "</ul>").show();
    } else {
      // If it doesn't need to be visible, don't show it
      $(msgContainer).html("").hide();
    }
  };
  var handleAjaxRequest = function() {
    // Toggle form
    toggleForm();
    // Show the loading animation
    $(form).find("fieldset").before('<p class="thanks">Thanks, we look forward to doing business with you. We\'ll be in touch soon.</p><p class="thanks"></p>');
    // Send ajax request
    $.post($(form).attr("action"), $(form).serialize(), handleAjaxResponse);
  };
  var handleAjaxResponse = function(data) {
    // Remove loading
    $(form).find("img.loading").remove();
    // Add thanks
    $(form).find("h1").after('<p class="thanks">Thanks, we look forward to doing business with you. We\'ll be in touch soon.</p><p class="thanks"><a href="#" title="Close window" class="close-window">Close window</a></p>');
    $(form).find("a.close-window").bind("click", function(e) {
      $(form).dialog('destroy');
      e.preventDefault();
    });
  };
  // First, we want to hide the form and replace it with a link to open the form in a modal
  // As at November 16 2009 no lightbox integration se we are displaying the form in the page.
  //$(form).hide();
  //$(form).before('<p><a href="#" title="" class="request-a-call-back">Request a call back</a></p>');
  //triggers = $("a.request-a-call-back");
  // Trigger the set up of optional fields in the form
  setupOptionals();
  // Add ajax to form
  handleForm();
  // Bind the lightbox to each trigger
  //$(triggers).bind("click", function(e) {
    // Open the lightbox
   // addLightBox();
    // Prevent default click action
   // e.preventDefault();
  //});
  
};
var initRequestCallBackLightboxV2 = function() {
  
  var form = $("#request-a-call-back-formV2"),
      triggers;
      
  if ($(form).length <= 0) {
    return;
  }
  
  // Define add lightbox function
  var addLightBox = function() {  
    $(form).dialog({
      modal: true,
      draggable: false,
      resizable: false,
      title: '<img src="/business_reddot/images/global/vodafone_logo.gif" alt="Vodafone Logo" />',
      width: 560,
      position: ['center', 63],
      dialogClass: 'request-a-call-back-container',
      closeText: 'Close window',
      open: function(e) {
        checkLightboxContents();
      },
      close: function(e) {
        $(this).dialog('destroy');
      }
    });
  };
  // This function adds functionality to show/hide optional form fields
  var setupOptionals = function() {
    $(form).find("a.toggle-optional").bind("click", function(event) {
      $(this).parent("div.optional-container").toggleClass("show-optional").toggleClass("hide-optional");
      event.preventDefault();
    });
  };
  // This function toggles the form's text and fields visibility
  var toggleForm = function() {
    $(form).find("fieldset").toggle();
  };
  // This function is used upon opening to make sure that the opened dialog contains the form and not a thankyou from a previously submitted form
  var checkLightboxContents = function() {
    var thanks = $(form).find("p.thanks");
    if (thanks.length > 0) {
      // Remove any existing thankyou
      $(thanks).remove();
      // Clear the form
      $(form)[0].reset();
      // Toggle visibility of the form
      toggleForm();
      // Hide optional
      $(form).find(".optional-container").each(function() {
        // If this optional is hidden, leave it alone
        if ($(this).hasClass("hide-optional")) {
          return;
        } else {
          $(this).toggleClass("hide-optional").toggleClass("show-optional");
        }
      });
    }
  };
  // We want this form to use AJAX for submission
  var handleForm = function() {
    // When this form is submitted, it is to be validated and then sent via XHR
    $(form).validate({
      submitHandler: handleAjaxRequest,
      showErrors: handleFormValidationErrors,
      onclick: false,
      onkeyup: false,
      onfocusout: false,
      rules: {
        last_name: "required",
        contact_number: "number required",
        required_number_of_connections: "number required",
       // industry: "required",
        state: "required",
       // existing_customer: "required",
        email: "email required"
      },
      messages: {
        last_name: "Please enter your contact name",
        contact_number: "Enter your contact number",
        required_number_of_connections: "Enter your required number of connections",
        // industry: "Select your industry type",
        state: "Select your state",
        // existing_customer: "Are you an existing Vodafone customer?",
        email: "Please enter a valid email address"
      }
    });
  };
  var handleFormValidationErrors = function(errorMap, errorList) {
    var errorMessages = [],
        msgContainer = $("#error-messages");
    // Style invalid inputs
    $.each(errorList, function() {
      // Find the element's parent li
      var container = $(this.element).parents(".formList > li");
      // Add the error class if it needs it
      if (!$(container).hasClass("error")) {
        $(container).addClass("error");
      }
      // Add the message to the error messages array
      errorMessages.push('<li><label for="' + $(this.element).attr("id") + '">' + this.message + '</label></li>');
    });
    // Now, go through each li.error and make sure the field is supposed to be errored
    $(form).find(".formList > li.error").each(function() {
      // Find this li element's input(s)
      var fields = $(this).find("input, select, textarea"),
          fieldErrors = $.map(fields, function(el, i) {
            // Return whether this field has an error on it or not
            return (errorMap[$(el).attr("name")] !== undefined);
          });
      // If the fieldErrors array doesn't contain any true values
      if ($.inArray(true, fieldErrors) < 0) {
        // Remove the error class
        $(this).removeClass("error");
      }
    });
    // If the message container needs to be visible, show it
    if (errorMessages.length > 0) {
      // Show messages
      $(msgContainer).html("<p><strong>Please complete the following items:</strong></p><ul>" + errorMessages.join("\n") + "</ul>").show();
    } else {
      // If it doesn't need to be visible, don't show it
      $(msgContainer).html("").hide();
    }
  };
  var handleAjaxRequest = function() {
    // Toggle form
    toggleForm();
    // Show the loading animation
    $(form).find("fieldset").before('<p class="thanks">Thanks, we look forward to doing business with you. We\'ll be in touch soon.</p><p class="thanks"></p>');
    // Send ajax request
    $.post($(form).attr("action"), $(form).serialize(), handleAjaxResponse);
  };
  var handleAjaxResponse = function(data) {
    // Remove loading
    $(form).find("img.loading").remove();
    // Add thanks
    $(form).find("h1").after('<p class="thanks">Thanks, we look forward to doing business with you. We\'ll be in touch soon.</p><p class="thanks"><a href="#" title="Close window" class="close-window">Close window</a></p>');
    $(form).find("a.close-window").bind("click", function(e) {
      $(form).dialog('destroy');
      e.preventDefault();
    });
  };
  // First, we want to hide the form and replace it with a link to open the form in a modal
  // As at November 16 2009 lightbox is at version2.
  $(form).hide();
  $(form).before('<p><a href="#" title="" class="request-a-call-back">Request a call back</a></p>');
  triggers = $("a.request-a-call-back");
  // Trigger the set up of optional fields in the form
  setupOptionals();
  // Add ajax to form
  handleForm();
  // Bind the lightbox to each trigger
  $(triggers).bind("click", function(e) {
    // Open the lightbox
    addLightBox();
    // Prevent default click action
    e.preventDefault();
  });
  
};
//Tab switcher - initialisation 
//tabContainerId = ID of tab container
function initTabs(tabContainerId){
var tabContainer = document.getElementById(tabContainerId); 
if (!tabContainer) return;
var divSet = tabContainer.getElementsByTagName('div');
var firstTabFlag=0;
for (var i=0; i<divSet.length; i++) {
 if (divSet[i].className=='tabcontent') {
   if (!firstTabFlag) {
     divSet[i].className='';
     firstTabFlag=1;
   } else {
     divSet[i].className='hidden';
   }
 }
}
}
//Tab switcher
//container = ID of tab container, must be used if more than one tab module is used on page (optional usage if only one tab module is displayed on a page )
//tab = ID of tab (mandatory)
function showTab(tab, container){
    if(typeof(container)=='undefined') {
        container='';
    }
    var i=1;
    do{
        document.getElementById(container+"tab"+i).className = "tab";
        document.getElementById(container+"tab"+i+"content").style.display="none";
        if (document.getElementById('hoPlus')) { document.getElementById('hoPlus').style.display="none"};
        i++;
    }
    while(document.getElementById(container+"tab"+i));
    document.getElementById(container+tab+"content").style.display="block";
    document.getElementById(container+tab).className = "activeTab";
    
    //if plus icon present check for both tab 1 showing
    if (document.getElementById('hoPlus')) {
        if (tab == "tab1") {
            //check to see if both tab1's showing
            if (document.getElementById("tabContainer1tab1content").style.display=="block" | document.getElementById("tabContainer1tab1content").style.display=="" && document.getElementById("tabContainer2tab1content").style.display=="block" | document.getElementById("tabContainer2tab1content").style.display=="") {
                document.getElementById('hoPlus').style.display="block";
            }
        }
    }
}
// lightbox for email a colleague form
var initEmailAColleagueLightboxEmail = function() {
  
  var form = $("#email-a-colleague-form"),
      triggers;
      
  if ($(form).length <= 0) {
    return;
  }
  
  // Define add lightbox function
  var addLightBox = function() {  
    $(form).dialog({
      modal: true,
      draggable: false,
      resizable: false,
      title: '<img src="/business_reddot/images/global/vodafone_logo.gif" alt="Vodafone Logo" />',
      width: 560,
      position: ['center', 63],
      dialogClass: 'email-a-colleague-container',
      closeText: 'Close window',
      open: function(e) {
        checkLightboxContents();
      },
      close: function(e) {
        $(this).dialog('destroy');
      }
    });
  };
  // This function adds functionality to show/hide optional form fields
  var setupOptionals = function() {
    $(form).find("a.toggle-optional").bind("click", function(event) {
      $(this).parent("div.optional-container").toggleClass("show-optional").toggleClass("hide-optional");
      event.preventDefault();
    });
  };
  // This function toggles the form's text and fields visibility
  var toggleForm = function() {
    $(form).find("fieldset").toggle();
  };
  // This function is used upon opening to make sure that the opened dialog contains the form and not a thankyou from a previously submitted form
  var checkLightboxContents = function() {
// Clear the form
      $(form)[0].reset();
    var thanks = $(form).find("p.thanks");
    if (thanks.length > 0) {
      // Remove any existing thankyou
      $(thanks).remove();
      // Clear the form
      $(form)[0].reset();
      // Toggle visibility of the form
      toggleForm();
      // Hide optional
      $(form).find(".optional-container").each(function() {
        // If this optional is hidden, leave it alone
        if ($(this).hasClass("hide-optional")) {
          return;
        } else {
          $(this).toggleClass("hide-optional").toggleClass("show-optional");
        }
      });
    }
  };
  // We want this form to use AJAX for submission
  var handleForm = function() {
    // When this form is submitted, it is to be validated and then sent via XHR
    $(form).validate({
      submitHandler: handleAjaxRequest,
      showErrors: handleFormValidationErrors,
      onclick: false,
      onkeyup: false,
      onfocusout: false,
      rules: {
        recipient_email: "email required",
        sender_email: "email required",
        sender_name: "required"
        
      },
      messages: {
        recipient_email: "Please enter your colleague's email address",
        sender_email: "Please enter your email address",
        sender_name: "Please enter your name"
      }
    });
  };
  var handleFormValidationErrors = function(errorMap, errorList) {
    var errorMessages = [],
        msgContainer = $("#error-messages");
    // Style invalid inputs
    $.each(errorList, function() {
      // Find the element's parent li
      var container = $(this.element).parents(".formList > li");
      // Add the error class if it needs it
      if (!$(container).hasClass("error")) {
        $(container).addClass("error");
      }
      // Add the message to the error messages array
      errorMessages.push('<li><label for="' + $(this.element).attr("id") + '">' + this.message + '</label></li>');
    });
    // Now, go through each li.error and make sure the field is supposed to be errored
    $(form).find(".formList > li.error").each(function() {
      // Find this li element's input(s)
      var fields = $(this).find("input, select, textarea"),
          fieldErrors = $.map(fields, function(el, i) {
            // Return whether this field has an error on it or not
            return (errorMap[$(el).attr("name")] !== undefined);
          });
      // If the fieldErrors array doesn't contain any true values
      if ($.inArray(true, fieldErrors) < 0) {
        // Remove the error class
        $(this).removeClass("error");
      }
    });
    // If the message container needs to be visible, show it
    if (errorMessages.length > 0) {
      // Show messages
      $(msgContainer).html("<p><strong>Please complete the following items:</strong></p><ul>" + errorMessages.join("\n") + "</ul>").show();
    } else {
      // If it doesn't need to be visible, don't show it
      $(msgContainer).html("").hide();
    }
  };
  var handleAjaxRequest = function() {
    // Toggle form
    toggleForm();
    // Show the loading animation
    $(form).find("fieldset").before('<p class="thanks">Thank you, all done.</p><img src="/business_reddot/images/global/loading_email.gif" alt="Loading&hellip;" width="32" height="32" class="loading"/>');
    // Send ajax request
    $.post($(form).attr("action"), $(form).serialize(), handleAjaxResponse);
  };
  var handleAjaxResponse = function(data) {
    // Remove loading
    $(form).find("img.loading").remove();
    // Add thanks
    $(form).find("h1").after('<p class="thanks">Thanks, we have emailed your colleague. .</p><p class="thanks"><a href="#" title="Close window" class="close-window">Close window</a></p>');
    $(form).find("a.close-window").bind("click", function(e) {
      $(form).dialog('destroy');
      e.preventDefault();
    });
  };
  // First, we want to hide the form and replace it with a link to open the form in a modal
  $(form).hide();
  $(form).before('<a href="#" title="Email a colleague a link to this page" class="email email-a-colleague">Email a colleague</a>');
  triggers = $("a.email-a-colleague");
  // Trigger the set up of optional fields in the form
  setupOptionals();
  // Add ajax to form
  handleForm();
  // Bind the lightbox to each trigger
  $(triggers).bind("click", function(e) {
    // Open the lightbox
    addLightBox();
    // Prevent default click action
    e.preventDefault();
  });
  
};
// end email a colleague lightbox  
// Execute on dom ready
$(function() {
  // Initialise the hot deals carousel
   initCarousel();
  
  // Initialise the plans listing
   initPlansListing();
  
  // Add support for lightbox with "request a call back" link
   initRequestCallBackLightbox();
     // Add support for lightbox with "request a call back" link
   initRequestCallBackLightboxV2();
  
  // Add support for lightbox with "email a colleague" link
  initEmailAColleagueLightboxEmail();
  
});
// alert('oo00[--0-0o');
var initCarousel = function() {
  
  var carousel = $("#carousel-viewport"),
      items = $("#product-items"),
      api,
      fixItemBorders;
  
  // Make sure the markup for the carousel is present
  if (($(carousel).length <= 0) || ($(items).length <= 0)) {
    //alert('nothing in eshop..js..business.js');
    return;
  }
  
  // Initialise the hot deals carousel found on the business home page and the phones and devices carousel found on the medium business home page
  if ($(carousel).hasClass("horizontal")) {
    // Add the left and right scroll controls
    $('<a href="#" title="Scroll left" id="scroll-left">&lt; Scroll left</a><a href="#" title="Scroll right" id="scroll-right">Scroll right &gt;</a>').insertAfter(carousel);
    // Initialise the carousel
    api = $(carousel).scrollable({
      loop: true,
      size:3,
      clickable: false,
      items: "#product-items",
      api: true
    });
    
    // Add scroll funcionality to controllers
    $("#scroll-left").click(function() { 
      api.prev(); // Up
      return false;
    });
    $("#scroll-right").click(function() { 
      api.next(); // Down
      return false;
    });
    
    return;
  }
  
  // Initialise the devices carousel on the small business home page
  if ($(carousel).hasClass("vertical")) {
    // Add the up and down scroll controls
    $('<a href="#" title="Scroll up" id="top-scroll-up" class="scroll-up">Scroll up</a><a href="#" title="Scroll down" id="top-scroll-down" class="scroll-down">Scroll down</a><a href="#" title="Scroll up" id="bottom-scroll-up" class="scroll-up">Scroll up</a><a href="#" title="Scroll down" id="bottom-scroll-down" class="scroll-down">Scroll down</a>').insertAfter(carousel);
    // Initialise the carousel
    api = $(carousel).scrollable({
      vertical: true,
      loop: true,
      size:5,
      clickable: false,
      keyboard: false,
      items: "#product-items",
      api: true
    });
    
    // Add scroll funcionality to controllers
    $(".scroll-up").click(function() { 
      api.next(); // Up
      return false;
    });
    $(".scroll-down").click(function() { 
      api.prev(); // Down
      return false;
    });
    
    // Now, all items in the scroller have a dotted border at the top (as a bg image)
    // The top one which is visible should _not_ have this border
    // This is the function for fixing up the top border
    fixFirstItem = function() {
      // Remove the 'no-bg' class from all items
      $("#product-items li").each(function() {
        if ($(this).hasClass('no-bg')) {
          $(this).removeClass('no-bg');
        }
      });
      // We'll use the scrollable api to find what's visible and add the 'no-bg' class to the first one
      $(api.getVisibleItems()[0]).addClass('no-bg');
    };
    // Execute it on initialisation of the carousel
    fixFirstItem();
    // And on each scroll
    api.onSeek(fixFirstItem);
    
    return;
  }
  
};
